君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

Angular2/4のLifecycle Hooksを理解する(ngOnInit編)

Angular2/4のLifecycle Hooksを理解する

Angular2/4のLifecycle Hooksのうち、ngOnInitについて簡単な実験をして、

どのタイミングでngOnInitが発火するのか確かめてみることにします。

前提

以下のような親子関係があるとします。

親Componentから子Componentへ、parentValueという値が渡されているとしましょう。

0. プロジェクトを立ち上げて、必要なComponentを生成する

ng new lifecycle-oninit
ng g component child

1. templateファイルを以下のように修正

<!-- app.component.html ->
<app-child [parentValue]="parentValue"></app-child>

親ComponentであるAppComponentから、parentValueを受け取るようにします。

2. ChildComponentにInputを追記

/** child/child.component.ts */
import {
  Component,
  Input, // 追記
  OnInit // 追記
} from '@angular/core';
export class ChildComponent implements
OnInit // 追記
{
  @Input() parentValue; // 追記

  /** ここから */
  constructor() {
    console.log(this.parentValue);
    console.log("@@@constructor");
  }

  ngOnInit() {
    console.log(this.parentValue);
    console.info("@@@ngOnInit");
  }
  /** ここまで追記 */
}

親からparentValueを受け取れるように、@Input()を追加します。

3. AppComponentにparentValueを追記

/** app.component.ts */
export class AppComponent
{
  public parentValue = '親の値だよ';
}

ログをみてみる

f:id:karoten512:20171003222416p:plain

ログを見てみると、

constructor → ngOnInit

の順で呼ばれていることがわかります。

また、ChildComponentが生成された時点(constructorが呼ばれた時点)では、

親からのInputをまだ受け取っていないことがわかります。

ngOnInitが実行された時点では、親からのInputを受け取っています。

つまり、ngOnInitが実行されるタイミングは、

Inputを受け取ったあと

ということになります。

Angular公式ドキュメントでは

Use ngOnInit() for two main reasons:

1. To perform complex initializations shortly after construction.
2. To set up the component after Angular sets the input properties.

上にあるように、

constructionの後に実行される「複雑な初期化」を行うときや、

inputプロパティがセットされた後にcomponentをset upする際に使われるようです。

参考:https://angular.io/guide/lifecycle-hooks