親子コンポーネント間の値の受け渡し
少し特殊な書き方をするので備忘録。
親から子への受け渡し
親側の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
Author And Source
この問題について(親子コンポーネント間の値の受け渡し), 我々は、より多くの情報をここで見つけました https://qiita.com/mounntainn/items/42acd136130763b13f36著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .