親子コンポーネント間の値の受け渡し


少し特殊な書き方をするので備忘録。

親から子への受け渡し

親側のhtmlで子コンポーネントのプロパティへ渡したい値を設定。
子コンポーネント側では@Inputデコレータを使って受けとる。

親コンポーネント側

parent.component.ts
export class ParentComponent {
  parentValue: string = "hoge";
}
parent.component.html
  <app-child
      [valueFromParent]="parentValue">
  </app-child>

子コンポーネント側

child.component.ts
import { Input } from '@angular/core';

export class ChildComponent {
  @Input() valueFromParent : string;
}

子から親への受け渡し

こちらは少し特殊になります。

子側で@Outputデコレータを使ったEventEmitterを使い、
親側でイベントをトリガーさせて親側へ値を渡します。

子コンポーネント側

child.component.ts
import { Output } from '@angular/core';

export class ChildComponent {
  childValue: string = "hoge";
  @Output() onChild: EventEmitter = new EventEmitter<string>();

  onBtnClick(){
    this.onChild.emit(this.childValue);
  }
}

親コンポーネント側

parent.compoment.html
  <app-child
      (onChild)="onChildInParent($event)">
  </app-child>
parent.component.ts
export class ChildComponent {
  parentValue = "";

  onChildInParent(valueFromChild: string){
    this.parentValue = valueFromChild;
  }
}

参考

Angular 親コンポーネントから子コンポーネントにデータの渡し方
Angular 公式リファレンス Component interaction