0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Angular】コンポーネント間でのデータの受け渡し方法

Posted at

はじめに

今回は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>

子から親へデータを渡す方法

@outputEventEmitterを使用して、親コンポーネントに値を渡します。

  • 親コンポーネント
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オブジェクトからユーザー入力を取得する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?