Angular 2 の @Input と @Output を使ってコンポーネント間でデータをやり取りする方法

2024-06-21

Angular 2 でコンポーネント間でオブジェクトを渡す方法

@Inputを使って親コンポーネントから子コンポーネントへデータを渡す

@Input ディレクティブは、親コンポーネントから子コンポーネントへデータを渡すために使用されます。

例:

親コンポーネント (parent.component.ts):

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {

  hero = {
    id: 1,
    name: 'Superman',
    powers: ['Flight', 'Super Strength', 'Laser Vision']
  };

  constructor() { }

  ngOnInit() { }
}
<app-child [hero]="hero"></app-child>
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {

  @Input() hero: any;

  constructor() { }

  ngOnInit() { }
}
<h2>{{hero.name}}</h2>
<ul>
  <li *ngFor="let power of hero.powers">{{power}}</li>
</ul>

上記コードの説明:

  • 親コンポーネント (parent.component.ts) で、hero というオブジェクト変数を定義します。
  • 親コンポーネントのテンプレート (parent.component.html) で、app-child コンポーネントタグに [hero]="hero" というバインディングを使用し、hero オブジェクトを子コンポーネントに渡します。
  • 子コンポーネント (child.component.ts) で、@Input ディレクティブを使用して hero プロパティを定義し、親コンポーネントから渡されたオブジェクトを受け取ります。
  • 子コンポーネントのテンプレート (child.component.html) で、hero オブジェクトのプロパティ (namepowers) を表示します。

@Outputを使って子コンポーネントから親コンポーネントへイベントを発行し、データを渡す

@Output ディレクティブと EventEmitter クラスは、子コンポーネントから親コンポーネントへイベントを発行し、イベントと共にデータを渡すために使用されます。

import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {

  @Input() hero: any;

  @Output() onHeroClicked = new EventEmitter<any>();

  constructor() { }

  ngOnInit() { }

  onClick() {
    this.onHeroClicked.emit(this.hero);
  }
}
<h2>{{hero.name}}</h2>
<button (click)="onClick()">Click Me</button>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {

  hero = {
    id: 1,
    name: 'Superman',
    powers: ['Flight', 'Super Strength', 'Laser Vision']
  };

  constructor() { }

  ngOnInit() { }

  onHeroClicked(hero) {
    console.log('Hero clicked:', hero);
  }
}
<app-child [hero]="hero" (onHero



Angular 2 でコンポーネント間でオブジェクトを渡すサンプルコード

親コンポーネントから子コンポーネントへデータを渡す

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {

  hero = {
    id: 1,
    name: 'Superman',
    powers: ['Flight', 'Super Strength', 'Laser Vision']
  };

  constructor() { }

  ngOnInit() { }
}
<app-child [hero]="hero"></app-child>
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {

  @Input() hero: any;

  constructor() { }

  ngOnInit() { }
}
<h2>{{hero.name}}</h2>
<ul>
  <li *ngFor="let power of hero.powers">{{power}}</li>
</ul>
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {

  @Input() hero: any;

  @Output() onHeroClicked = new EventEmitter<any>();

  constructor() { }

  ngOnInit() { }

  onClick() {
    this.onHeroClicked.emit(this.hero);
  }
}
<h2>{{hero.name}}</h2>
<button (click)="onClick()">Click Me</button>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {

  hero = {
    id: 1,
    name: 'Superman',
    powers: ['Flight', 'Super Strength', 'Laser Vision']
  };

  constructor() { }

  ngOnInit() { }

  onHeroClicked(hero) {
    console.log('Hero clicked:', hero);
  }
}
<app-child [hero]="hero" (onHeroClicked)="onHeroClicked($event)"></app-child>
  • 子コンポーネント (child.component.ts) で、@Output ディレクティブと EventEmitter クラスを使用して onHeroClicked というイベント



Angular 2 でコンポーネント間でオブジェクトを渡すその他の方法

サービスを使う

サービスは、コンポーネント間で共有できるデータとロジックを格納するための良い方法です。コンポーネント間でオブジェクトを渡すために、サービスを使用してオブジェクトを格納し、他のコンポーネントからそのオブジェクトにアクセスできるようにすることができます。

hero.service.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class HeroService {
  private hero: any = {
    id: 1,
    name: 'Superman',
    powers: ['Flight', 'Super Strength', 'Laser Vision']
  };

  constructor() { }

  getHero() {
    return this.hero;
  }

  setHero(hero) {
    this.hero = hero;
  }
}
import { Component, OnInit } from '@angular/core';
import { HeroService } from './hero.service';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {

  constructor(private heroService: HeroService) { }

  ngOnInit() { }

  getHero() {
    console.log(this.heroService.getHero());
  }

  setHero(hero) {
    this.heroService.setHero(hero);
  }
}
import { Component, Input, OnInit } from '@angular/core';
import { HeroService } from './hero.service';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {

  constructor(private heroService: HeroService) { }

  ngOnInit() { }

  getHero() {
    console.log(this.heroService.getHero());
  }

  setHero(hero) {
    this.heroService.setHero(hero);
  }
}

この例では:

  • HeroService というサービスを作成します。
  • このサービスには、getHero()setHero() という 2 つのメソッドがあります。
  • getHero() メソッドは、サービスに格納されているヒーローオブジェクトを返します。
  • 親コンポーネント (parent.component.ts) は、HeroService を注入し、getHero()setHero() メソッドを使用してヒーローオブジェクトを取得および設定します。

RxJS は、Reactive Programming を JavaScript で実装するためのライブラリです。RxJS を使用して、コンポーネント間でオブジェクトを Observable として発行し、購読することができます。

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {

  @Output() heroClicked = new EventEmitter<any>();

  constructor() { }

  ngOnInit() { }

  onClick() {
    const hero = {
      id: 1,
      name: 'Superman',
      powers: ['Flight', 'Super Strength', 'Laser Vision']
    };

    const heroObservable = of(hero);
    this.heroClicked.emit(heroObservable);
  }
}
import { Component, OnInit, Input } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {

  @Input() heroObservable: Observable<any>;

  constructor() { }

  ngOnInit() {
    this.heroObservable.subscribe(hero => console.log('Hero clicked:', hero));
  }
}

angular angular2-directives


Angular 2 *ngForでCustom Pipeを使用して逆転する方法

Angular 2のngForディレクティブは、配列をテンプレート内の要素に反復処理するために使用されます。しかし、場合によっては、配列を逆順に反復処理したい場合があります。逆転方法*ngForを逆転するには、以下の2つの方法があります。配列を逆順にソートするには、以下のコードを使用できます。...


Angular2でタイマーの値をより柔軟に制御する方法

コンポーネントを作成するまず、タイマーを表示するコンポーネントを作成する必要があります。このコンポーネントには、タイマーの値を表示するテンプレートと、タイマーを制御するロジックが含まれます。モジュールにコンポーネントを登録する次に、コンポーネントをモジュールに登録する必要があります。...


【保存版】Angular、TypeScript、RxJSで発生するrxjs/Subject.d.tsエラー:原因、対策、回避策を完全網羅

このエラーは、TypeScript 2.4 以降で RxJS 5.5 以前を使用している場合に発生します。RxJS 5.5 以降では、Subject クラスの lift プロパティの型が変更されましたが、rxjs/Subject. d.ts ファイルの型定義は古いままになっています。そのため、TypeScript コンパイラは、Subject クラスが Observable クラスを誤って拡張しているというエラーを出力します。...


型が違う?参照を変更?Angular 4で「Error: Cannot assign to a reference or variable!」エラーが発生する理由

原因と解決策変数の宣言と初期化変数に値を割り当てる前に、その変数が正しく宣言されていることを確認する必要があります。変数が宣言されていない場合、このエラーが発生します。参照の変更参照は、オブジェクトへのエイリアスです。参照を変更しようとすると、このエラーが発生します。参照を変更するには、=演算子ではなくObject...


設定ファイルでファイルを無効化?Angular, TypeScript, Angular CLI の警告解決

この警告は、.ts ファイルが TypeScript コンパイルで使用されているものの、実際に使用されていないことを示します。これは、コードに不要な部分が残っている可能性があり、コードの保守性やパフォーマンスに悪影響を及ぼす可能性があることを意味します。...


SQL SQL SQL SQL Amazon で見る



【実践ガイド】Angular 2 コンポーネント間データ共有:サービス、共有ステート、ルーティングなどを活用

@Input と @Output@Input は、親コンポーネントから子コンポーネントへデータを一方方向に送信するために使用されます。親コンポーネントで @Input() デコレータ付きのプロパティを定義し、子コンポーネントのテンプレートでバインディングすることで、親コンポーネントのプロパティ値を子コンポーネントに渡すことができます。