@ViewChildとAfterViewInitをつかってデータを渡す方法
- @ViewChild
- AfterViewInit
を使ってコンポーネント間でデータを渡す。
これらを使えば子コンポーネントを参照し、親コンポーネント内の変数にアクセスできる。
環境
- Angular: v9.0.4
- Node: v12.16.1
- OS: win32 x64
準備
以下を生成しておく
- Angular プロジェクト
- parent.component
- child.component
app.component
app.componentに生成した親コンポーネントを追加
app.component.html
<app-parent></app-parent>
child.componentの実装
子コンポーネントには親に渡したいデータを用意しておく
child.component.ts
/*
省略
*/
export class ChildComponent implements OnInit {
childValue = 'Hello World'; // 追加
constructor() { }
ngOnInit(): void {
}
}
childValueという変数を用意。
parent.componentの実装
親がわでは、ViewChildとAfterViewInitと参照したい子コンポーネントをimportしておく。
parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from '../child/child.component';
子のデータを受け取るようの変数を用意。
ViewChildデコレータで参照する子コンポーネントを設定する。
ngAfterViewInit()で子の値を受け取る。
parent.component.ts
// デフォルトだとimplements OnInit になっているので注意
export class ParentComponent implements AfterViewInit {
parentValue: string;
// 参照子コンポーネントを設定。
@ViewChild(ChildComponent) childReference;
constructor() { }
ngAfterViewInit() {
this.parentValue = this.childReference.childValue;
}
}
parent.component.html
<div>
<app-child-view></app-child-view>
<p>{{parentValue}}</p>
</div>
parentValueにはHelloと表示される。
終わり。
おまけ
ngAfterViewInit()って?
ngOnInit()って?
という人向け
ライフサイクル・フック
ライフサイクル・フック:コンポーネントの生成、更新、破棄などのタイミングで発生するように行動させるもの
- ngOnInit():コンポーネント生成直後に呼び出される。OnInitインタフェースのときに存在する。
- ngAfterViewInit():コンポーネントのビューと子のビューを初期化した後に呼び出される。ちなみにこれと併用して使えるライフサイクル・フックもある。(ngAfterViewCheckedなど)
くわしくは公式ドキュメント(https://angular.jp/guide/lifecycle-hooks)
次
知らないor使ったことないライフサイクル・フックが結構あるので実際に使ってみてからまとめてみます。