2019年2月23日土曜日

Angular Reactive Forms(リアクティブフォーム)の使い方

Angular で提供されている Reactive Forms(リアクティブフォーム)の使い方を見てみましょう。

AppModule.ts

Reactive Forms を利用するため、@angular/forms から ReactiveFormsModule をインポートします。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


AppComponent.ts

コンポーネント上では、@angular/forms から FormBuilder をインポートします。
各入力フォームコントロールは FormControl で生成します。そして、これら入力フォームコントロールをまとめ上げるのが、group メソッドの役割です。

import { Component } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';

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

  id = new FormControl('');
  password = new FormControl('');

  loginForm = this.fb.group({
    id: this.id,
    password: this.password
  });

  constructor(private fb: FormBuilder) {

  }

  login() {
    console.log('id: ', this.loginForm.get('id').value);
    console.log('password: ', this.loginForm.get('password').value);
  }
}


AppComponent (HTML テンプレート) 


HTML テンプレート上では、form タグの formGroup 属性に、コンポーネントで生成した FormGroup(loginForm) を指定します。form タグ配下の入力コントロールには、formControl 属性から FormControl を紐づけます。
<form [formGroup]="loginForm" (ngSubmit)="login()">
  <input type="text" [formControl]="id">
  <input type="password" [formControl]="password">
  <input type="submit" value="ログイン">
</form>

ngSubmit に登録されている login() メソッドでは、FormGroup から FormControl を取り出して値を出力しています。


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

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

2019年2月22日金曜日

Angular HttpClient を利用した HTTP 通信

Angular で HTTP 通信を行う際には、HttpClient を利用します。


app.module.ts


@angular/common/http にある HttpClientModule をインポートします。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts


HttpClient を DI で参照します。HttpClient は HTTP 通信の動詞(get, post, put, delete など) に対応するメソッドが用意されています。用途に合うメソッドを呼び出します。ここでは、get メソッドでリソースの取得を行っています。データは subscribe することで取得することができます。

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) {

  }

  getData() {
    this.http.get('https://localhost:5001/api/items').subscribe(response => {
      console.log(response);
    });
  }
}

app.component.html


参考までに、AppComponent に対応する HTML テンプレートの実装を記述しておきます。

<button (click)="getData()">http 通信</button>


※ HTTP 通信をする際に、サーバー側でクロスオリジン制約により通信が弾かれてしまう場合、制限を解除して通信を行ってください。

参考:ASP.NET Core Web API クロスオリジンを許可する方法
https://kainobi2.blogspot.com/2019/01/aspnet-core-web-api.html


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

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

2019年2月21日木曜日

Angular ngFor ディレクティブによる繰り返し処理

Angular の ngFor ディレクティブを利用することで、HTML テンプレート上で繰り返し処理を行うことができます。

app.component.ts


簡単な例として、items という文字列配列があるとします。

import { Component, OnInit } from '@angular/core';

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

  ngOnInit() {
    for (let i = 0; i < 10; i++) {
      this.items.push(`item ${i}`);
    }
  }

}

app.component.html


HTML テンプレート上で、ngFor で items 配列のすべての要素を出力します。ngFor ディレクティブを div などの HTML 要素上で使う際には、*(アスタリスク)を付けます。

<div *ngFor="let item of items">
  {{ item }}
</div>



出力結果は次のとおりです。




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


Angular 機能紹介一覧

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

2019年2月20日水曜日

Angular CLI コマンドいろいろ

コンポーネントを生成するコマンド


ng generate component コンポーネント名

いろいろと省略すると、次のように書くことができます。
ng g c child

サービスを生成するコマンド


ng generate service サービス名
ng g s calc



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

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

2019年2月19日火曜日

Angular CLI ルーティング用ファイル付きのモジュールの作成

Angualr CLI でモジュールを作成する際に利用するコマンドは ng generate module です。
更に --routing というパラメーターを加えることで、ルーティング用ファイルを自動生成してくれます。例えば、product モジュールを作成する際に ルーティング用ファイルを自動生成する場合、次のようになります。

ng generate module product --routing

generate や module は g と m で省略することもできます。
ng g m product --routing


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

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

2019年2月18日月曜日

Angular CLI を利用したアプリケーション作成方法

Angular では CLI(Command Line Interface) が用意されており、CLI コマンドを利用することですばやくアプリケーション作成やアプリケーションの実行などを行うことができます。

Angular CLI を利用するにあたり、Angular CLI のインストールを行います。
npm install -g @angular/cli

続いてアプリケーションのひな型を生成します。
ng new app1

 app1 の部分にはアプリケーション名を入力します。すると、ルーティングなどの初期設定に関する選択肢が出てきます。デフォルトの選択値のまま処理を進めると、アプリケーションの雛形が作成されます。アプリケーション作成後、アプリケーションフォルダに移動し、次の CLI コマンドを入力することでアプリケーションを実行することができます。
ng serve -o

もしくは次のように serve を省略して書くこともできます。
ng s -o

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

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

2019年2月17日日曜日

Angular ngOnChanges イベント

Angular のイベントライフサイクルフックのうち、ngOnChanges イベントについて見ていきます。

ngOnChanges イベントは、コンポーネントの Input プロパティが設定(再設定)されたタイミングで発生します。また、ngOnInit の前に発生します。Angular のドキュメンテーションはこちらです。

ライフサイクル・フック
https://angular.jp/guide/lifecycle-hooks#lifecycle-sequence#ライフサイクル・シーケンス

以下は、AppComponent と ChildComponent がある場合に、ChildComponent の ngOnChanges イベントをハンドルする例です。


child.component.ts


ChildComponent には、displayTetxt というプロパティがあり、@Input デコレーターにより外部より値が設定できる状態になっています。それに加え、ngOnChanges イベントを実装しています。
 
import { Component, OnInit, OnChanges, SimpleChanges, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {
  @Input() displayText: string;

  constructor() { }

  ngOnInit() {
    console.log('child: ngOnInit');
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('child: ngOnChanges', changes);
  }
}

child.component.html


ChildComponent の HTML テンプレート上では、displayText を出力しています。
<p>
  child works!
</p>
{{displayText}}


続いて AppComponent 側の設定です。


app.component.html


AppComponent 側では、ChildComponent の持つ displayText に現在時刻を文字列として持つ変数をバインドしています。

<button (click)="changeDisplayText()">displayText を変更!</button>
<app-child #child [displayText]="text"></app-child>


app.component.ts


ボタンをクリックすることでバインドしている変数が変更されていきます。

import { Component } from '@angular/core';

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

  changeDisplayText() {
    this.text = new Date().toString();
  }
}


実行結果


ブラウザの開発者ツールのコンソールを見ると、ボタンクリックに応じて ngOnChanges が発生していることが確認できます。



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

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

2019年2月16日土曜日

JavaScript String.includes メソッド

JavaScript の String.includes メソッドを利用することで、文字列に任意の文字列が含まれているかを判定することができます。ES2015 から提供されています。例えば、次のように使います。

var str1 = "abcde";
str1.includes('c')
// true が返ります。

2019年2月15日金曜日

JavaScript Array - map メソッドと filter メソッド

JavaScript Array の map メソッドと filter メソッドについて、簡単にメモをしておきます。

map メソッド

配列の各要素に任意の加工を行い、新たに配列を生成します。

let items = [1, 2, 3, 4, 5];

let result = items.map((val, idx, data) => {
    return val * 5;
});

console.log('result: ', result);
console.log('items: ', items);


結果として、result には items の各要素を 5 倍した値が入っています。



 

filter メソッド

配列の各要素から、条件に合致する要素のみを取り出し、新たに配列を生成します。

let items = [1, 2, 3, 4, 5];
let result = items.filter((val, idx, data) => {
    return val > 3;
});

console.log('result: ', result);
console.log('items: ', items);

結果として、result には items から条件に合致した 4 と 5 が入っています。