2019年2月24日日曜日

Angular - Visual Studio Code でのデバッグ実行

Angular アプリケーションを Visual Studio Code 上でデバッグ実行する方法です。


Debugger for Chrome のインストール


Debugger for Chrome というエクステンションというがありますので、インストールします。





Visual Studio のデバッグ設定


Visual Studio のデバッグ設定を行います。虫マークのデバッグメニューをクリックし、「デバッグの開始」ボタンの右隣にあるドロップダウンを開きます。そこから、「構成の追加...」を選択します。




すると、コマンドパレットにデバッグの実行環境が一覧表示されます。ここから「Chrome」を選択します。




プロジェクトルート配下に .vscode\launch.json というファイルが生成され、開かれます。configurations > url で設定されているポートが 8080 になっているので、4200 に変更して保存します。

{
    // IntelliSense を使用して利用可能な属性を学べます。
    // 既存の属性の説明をホバーして表示します。
    // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:4200",
            "webRoot": "${workspaceFolder}"
        }
    ]
}


デバッグの開始


Angular アプリケーションを 4200 ポートで実行し、「デバッグの開始」ボタンをクリックします。(緑の再生ボタン)






デバッグ実行が始まると、Chrome ブラウザが立ち上がってきます。 Visual Studio Code 上でブレークポイントをはっておくと、処理が止まります。


 


ウォッチ式も使うことができます。




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

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

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