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 が発生していることが確認できます。
