2019年2月14日木曜日

Angular async パイプで HTML テンプレートに独自クラスのオブジェクトを表示

タイトルのままです。Angular で取り扱う独自クラスのオブジェクトのデータを、async パイプを使って HTML テンプレート上に表示する方法です。

例えば、独自実装の Album クラスオブジェクトの Observable (ここの例では album$)を受け取るコンポーネントがあった場合、コンポーネントの HTML テンプレート上では、async の後に別の変数を用意して受けます。この変数には album$ | async の評価後の値が入るので、HTML テンプレート内で利用することができます。

HTML テンプレート
<div *ngIf="album$ | async as album">
  <div>{{album.title}}</div>
</div>

コンポーネント
export class AlbumDetailComponent implements OnInit {
  ...

  album$: Observable<Album>;

  ngOnInit() {
    this.album$ = this.service.getAlbum();
  }
}


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月13日水曜日

Angular イベントバインディング


Angular のイベントバインディングを利用して、HTML テンプレート上にあるコントロールのイベントを、コンポーネント(TypeScript) 側でハンドルする方法です。

ここでは2つのボタンを用意し、一つは引数なし、もう一つは引数ありのイベントハンドラーを呼び出すようにしています。

ポイントは、HTML テンプレート上のイベントを丸かっこ () で囲むことでイベントバインディングを行うことができる部分です。

HTML テンプレート
<button (click)="clicked()">ボタン</button>
<button (click)="clickedWithNumber(1)">ボタン</button>

コンポーネント(TypeScript)
clicked() {
  console.log('クリックされました。');
}
clickedWithNumber(arg) {
  console.log('クリックされました。', arg);
}

Angular に関連するトピックは次のページにまとめてあります。


Angular 機能紹介一覧

https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月10日日曜日

Angular 機能紹介一覧

Angular 関連の機能紹介一覧です。

Angular 事始め

Angular 開発環境の構築
https://kainobi2.blogspot.com/2019/03/angular.html

Angular CLI を利用したアプリケーション作成方法
https://kainobi2.blogspot.com/2019/02/angular-cli.html

Angular CLI

Angular CLI ルーティング用ファイル付きのモジュールの作成
https://kainobi2.blogspot.com/2019/02/angular-cli_19.html

Angular CLI コマンドいろいろ
https://kainobi2.blogspot.com/2019/02/angular-cli_20.html

ディレクティブ

Angular - ngIf ディレクティブ
https://kainobi2.blogspot.com/2018/07/angular-ngif.html

Angular ngFor ディレクティブによる繰り返し処理
https://kainobi2.blogspot.com/2019/02/angular-ngfor.html

バインディング

Angular イベントバインディング
https://kainobi2.blogspot.com/2019/02/angular_13.html

デコレーター

Angular @ViewChild デコレーター
https://kainobi2.blogspot.com/2019/02/angular-viewchild.html

Angular @Input デコレーター
https://kainobi2.blogspot.com/2019/02/angular-input.html

フォーム

Angular ngModel 使い方
https://kainobi2.blogspot.com/2018/11/angular-ngmodel.html

Angular Reactive Forms(リアクティブフォーム)の使い方
https://kainobi2.blogspot.com/2019/02/angular-reactive-forms.html

ルーティング

Angular モジュールの lazy loading (遅延読み込み)
https://kainobi2.blogspot.com/2019/03/angular-lazy-loading.html

パイプ

Angular async パイプで HTML テンプレートに独自クラスのオブジェクトを表示
https://kainobi2.blogspot.com/2019/02/angular-async-html.html

HTTP 通信

Angular HttpClient を利用した HTTP 通信
https://kainobi2.blogspot.com/2019/02/angular-httpclient-http.html

Angular in-memory-web-api を使う
https://kainobi2.blogspot.com/2019/04/angular-in-memory-web-api.html

イベントライフサイクルフック

Angular ngOnChanges イベント
https://kainobi2.blogspot.com/2019/02/angular-ngonchanges.html

PWA

Angular アプリケーションの PWA 化
https://kainobi2.blogspot.com/2019/02/angular-pwa.html

ユーザー認証

Angular Firebase による Google アカウント認証(ログイン・ログアウト)の実装方法

その他

Angular 関連メモ
https://kainobi2.blogspot.com/2018/06/angular.html

Angular5 TODO リスト作成
https://kainobi2.blogspot.com/2018/02/angular5-todo.html

Angular メモ
https://kainobi2.blogspot.com/2017/09/angular.html

Netlify で Angular のルーティング利用時に必要な設定

Angular @ViewChild デコレーター

Angular では、HTML テンプレート上に定義されているコンポーネントを TypeScript 側から参照する機能として、@ViewChild デコレーターが提供されています。

例えば、AppComponent に次の MyLabelComponent を利用しているとします。


MyLabelComponent (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabelComponent (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

AppComponent の TypeScript 上で、@ViewChild デコレーターに型を指定するかたちで、MyLabelComponent を参照することができます。

AppComponent (TypeScript)
import { Component, ViewChild } from '@angular/core';
import { MyLabelComponent } from './my-label/my-label.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app1';

  @ViewChild(MyLabelComponent) myLabel: MyLabelComponent;

  getText() {
    console.log(this.myLabel.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label text="abc"></app-my-label>


なお、複数の MyLabelComponent が存在する場合、 テンプレート参照変数を利用してコンポーネントを特定します。(この例では、HTML テンプレート上の #label1 や #label2 がテンプレート参照変数です。)

 AppComponent (TypeScript)
export class AppComponent {
  title = 'app1';

  @ViewChild('label1') myLabel1: MyLabelComponent;
  @ViewChild('label2') myLabel2: MyLabelComponent;

  getText() {
    console.log(this.myLabel1.text);
    console.log(this.myLabel2.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label #label1 text="abc"></app-my-label>
<app-my-label #label2 text="def"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

Angular @Input デコレーター

Angular の @Input デコレーターは、親コンポーネントから子コンポーネントに対してデータを渡す際に使います。

例えば、子コンポーネントとして MyLabel コンポーネントがあるとします。

MyLabel コンポーネント (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabel コンポーネント (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

 コンポーネントに text プロパティを定義し、更に @Input デコレーターを付与しています。外部コンポーネントからは、@Input デコレーターの引数に指定している 'text' というプロパティを利用して値を渡すことができるようになります。※ 引数を省略すると、変数名(ここでは 'text')というプロパティ名になります。

親コンポーネントからは次のように利用しています。 text というプロパティ(インプット)に対して "abc" という文字列を指定しています。

App コンポーネント(HTML テンプレート)
<app-my-label text="abc"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月9日土曜日

RxJS Observable の pipe メソッドが便利

タイトルのままです。pipe メソッドの中に map メソッドを挟んで処理を加えていく感覚がようやく分かってきました。使いこなせるようになりたいです。

参考サイト
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-pipe

https://www.learnrxjs.io/operators/transformation/map.html

2019年2月7日木曜日

Netlify で Angular のルーティング利用時に必要な設定

Netlify に Angular のアプリケーションを配備しただけでは、Angular のルーティングが動作せずに 404 NotFound エラーが出ます。Netlify のサーバー上にファイルが見つからないためにこのエラーが出ているようです。エラーを解消して Angular のルーティングを動作させるためには、次の設定が必要でした。


1._redirects ファイルを作成します。
src フォルダ配下に "_redirects" という名前のファイルを作成します。


2._redirects ファイルの内容を加えます。(次の記述をコピペで OK です。)
/*    /index.html   200



3.angular.json の architect > build > options > assets に _redirects ファイルを指定します。

"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
...
"assets": [
"src/favicon.ico",
"src/assets",
"src/_redirects",//←ここを追加
],

これで Angular のリダイレクトが正しく動作するようになります。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月6日水曜日

Angular アプリケーションの PWA 化

Angular アプリケーションを PWA にする方法です。至って簡単で、次のコマンドを実行すると PWA になります。


ng add @angular/pwa --project=my-project  


my-project のところには、ご自身のプロジェクト名と置き換えて下さい。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年1月27日日曜日

ASP.NET Core Web API クロスオリジンを許可する方法


Angular でちょっとしたサーバーとの通信をテストする時に、Cors エラーを回避するために使っています😅設定は簡単で、Startup.cs で UseCors メソッドを下記のように実装します。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // 追加
        app.UseCors(builder =>
         builder
         .WithOrigins("http://localhost:4200")
         .AllowAnyHeader()
         .AllowAnyMethod());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

2019年1月15日火曜日

GitHub からコミットした履歴を消し去る方法

自分用のメモです。

最後のコミットを削除
git reset --hard HEAD~

結果をプッシュする
git push origin +master

2018年12月15日土曜日

GitBucket セットアップメモ

GitBucket のダウンロード
https://github.com/kohsuke/winsw/releases

winsw を遣って GitBucket をサービスとして登録する
https://github.com/kohsuke/winsw/releases

サービスの削除
sc delete gitbucket

2018年11月11日日曜日

Angular ngModel 使い方

Angular の ngModel の使い方をメモしておきます。黄色でハイライトされている部分を追加すると ngModel を利用できるようになります。

1.app.module.ts

ngModel は angular/forms の FormsModule に含まれているので、FormsModule をインポートします。また、NgModel デコレータの imports で FormsModule をインポートします。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';//追加

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//追加
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2.app.component.html

HTML テンプレートで ngModel に変数 name をバインドします。
<input type="text" [(ngModel)]="name">
{{name}}

3.app.component.ts

変数 name の初期値を設定します。
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  name = 'sasaki';//追加
}

Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2018年10月7日日曜日

ASP.NET Core Web API - html ファイルの利用

ASP.NET Core Web API で html ファイルを利用(表示)する方法です。

Startup.cs ファイルの Configure メソッドに、app.UseStaticFiles() を呼び出します。すると、wwwroot フォルダ配下の html ファイルを表示できるようになります。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
        app.UseStaticFiles(); //追加
    }
}