はじめに
今回はAngularでは使用頻度が高いコンポーネント間でのデータの受け渡し方法についてまとめました。
※まとめた後に気が付きましたが公式に詳細が載っていました😅
さらっと見たい方は私のページを、詳細を知りたい方は公式のページをご確認ください。
バージョン
- Angular: 9.1.11
バージョンの確認方法については過去記事に記載しております。
結論
公式
Angular:ディレクティブとコンポーネントの親子間でのデータ共有
親から子へデータを渡す方法
@input
を使用して親コンポーネントから子コンポーネントに値を渡しています。
- 親コンポーネント
parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit
{
parentData : string = "";
constructor() { }
ngOnInit() {
this.parentData = "child.componentへ渡すデータ";
}
}
parent.component.html
<div>
<app-child [childData]="parentData"></app-child>
<div>
- 子コンポーネント
child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit
{
@Input() childData: string = null;
constructor() { }
ngOnInit() {
}
}
child.component.html
<div>{{childData}}</div>
子から親へデータを渡す方法
@output
とEventEmitter
を使用して、親コンポーネントに値を渡します。
- 親コンポーネント
parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit
{
constructor() { }
ngOnInit() {
}
onReceiveData(event) {
console.log(event); // 子データ
}
}
parent.component.html
<div>
<!-- eventオブジェクトでデータが渡される -->
<app-child (childData)="onReceiveData($event)"></app-child>
<div>
- 子コンポーネント
child.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit
{
@Output() childData = new EventEmitter<string>();
constructor() { }
ngOnInit() {
}
submitData() {
this.childData.emit("子データ");
}
}
child.component.html
<div>
<button (click)="submitData()">親コンポーネントへデータを渡す</button>
</div>
参考文献
Angular:ディレクティブとコンポーネントの親子間でのデータ共有
Angular:Input
Angular:Output
Angular:EventEmitter
Angular:$eventオブジェクトからユーザー入力を取得する