![見出し画像](https://assets.st-note.com/production/uploads/images/86700116/rectangle_large_type_2_85b24003f34f197447761a841f085897.jpeg?width=1200)
Angular_@Input()で親コンポーネントから子コンポーネントへ値を引き渡す #263日目
Angularでは機能をコンポーネントに分けて実装していきますが、構造的に親となるコンポーネントと子となるコンポーネントが存在することになります。
その親子間でデータを受け渡しする必要がある場合、「@Input()」や「@Output()」というデコレーターで実装可能です。
@Input():
親→子へのデータの受け渡しを実装できます。
子であるコンポーネントクラスのプロパティの先頭に@Input()を付けると、そのプロパティは親コンポーネントからデータを受け取れるようになります。
@Output():
子→親へのデータの受け渡しを実装できます。
@Input()と同じように子側で定義しますが、データを受け渡す仕組みが異なります。親に直接データを渡すのではなく、データを含んだイベントを発生させて、それを親に拾ってもらうイメージです。この記事では詳細は割愛します。
@Input()で親コンポーネントから子コンポーネントへ値を引き渡す
@Input()デコレーターは子コンポーネントで設定します。Inputをインポートし、ここでは「hero」プロパティに設定しました。ちなみに「hero?」のクエスチョンマークは、そのプロパティを省略可能(必須ではない)にするためのオプションパラメーターです。
[hero-detail.component.ts] # 子コンポーネント
import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
@Input() hero?: Hero;
constructor() { }
ngOnInit(): void {
}
}
次に、データの受け渡し場所を設定します。親コンポーネントのテンプレート上で子コンポーネントの要素を定義し、その要素のheroプロパティにバインドさせます。<app-hero-detail>内にある[hero]="selectedHero"で、子コンポーネントのheroプロパティに、親コンポーネントのselecetedHeroの値が渡されていることになります。
[heros.component.html] # 親コンポーネントのテンプレート
<ul class=" heroes">
<li *ngFor="let hero of heroes">
<button [class.selected]="hero === selectedHero" type="button" (click)="onSelect(hero)">
<span class="badge">{{ hero.id }}</span>
<span class="name">{{ hero.name }}</span>
</button>
</li>
</ul>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
親コンポーネントがどのように定義されているか見ておきます。onSelect()メソッドで「selectedHero」に値を代入しています。
[heros.component.ts] # 親コンポーネント
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
selectedHero?: Hero;
constructor() { }
ngOnInit(): void {
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
}
この設定で親子間のデータの受け渡しのうち、親側からデータが渡せるようになります。
ここまでお読みいただきありがとうございました!!