[Angular] 「基本的なAngularアプリをはじめる」をやってみる(4)親コンポーネントにデータを渡す


「基本的なAngularアプリをはじめる」をやってみる(4)

[Angular] 「基本的なAngularアプリをはじめる」をやってみる(準備)

[Angular] 「基本的なAngularアプリをはじめる」をやってみる(1)

[Angular] 「基本的なAngularアプリをはじめる」をやってみる(2)

[Angular] 「基本的なAngularアプリをはじめる」をやってみる(3)子コンポーネントにデータを渡す

Angular のチュートリアルをやってみています。

親コンポーネントにデータを渡す

Angular公式ページ : 親コンポーネントにデータを渡す

Notify Meボタンを動作させるには、子コンポーネントが通知して親コンポーネントにデータを渡す必要があります。

1.product-alerts.component.ts で、Output と EventEmitter をインポートする
product-alerts.component.ts
import { Component } from '@angular/core';
import { Input } from '@angular/core';
import { Output, EventEmitter } from '@angular/core';
2.notify という名前のプロパティを @Output() デコレーターと EventEmitter() のインスタンスで定義する
product-alerts.component.ts
export class ProductAlertsComponent {
  @Input() product;
  @Output() notify = new EventEmitter();
}
3.Notify Meボタンをイベントバインディングで更新し、notify.emit()メソッドを呼び出す
product-alerts.component.html
<p *ngIf="product.price > 700">
  <button (click)="notify.emit()">Notify Me</button>
</p>
4.product-list.component.ts で onNotify() メソッドを定義
product-list.component.ts
export class ProductListComponent {
  products = products;
  test_1 = '製品';

  share() {
    window.alert('The product has been shared!');
  }

  onNotify() {
    window.alert('メッセージ : You will be notified when the product goes on sale');
  }
}

親の ProductListComponentは、ProductAlertsComponentがイベントを発生させたときに動作します。

5.product-list.component.html で、 を製品リストコンポーネントの onNotify() メソッドにバインドする
product-list.component.html
<button (click)="share()">
  shareボタン
</button>

<app-product-alerts
  [product]="product" 
  (notify)="onNotify()">
</app-product-alerts>

Notify Meボタンをクリックすると、下図のようなアラートが表示されるようになります。

ここまでで、いちおうAngularチュートリアルの入門編は終わりです。