Angular 2 Sibling Component Communication Ask Question

Angular 2 Sibling Component Communication Ask Question

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so there's no routing involved.

How do I tell DetailComponent what item in ListComponent was clicked?

親 (AppComponent) にイベントを発行し、親に @Input を使用して DetailComponent の selectedItem.id を設定させることを検討しました。または、監視可能なサブスクリプションを備えた共有サービスを使用することもできます。


編集:ただし、イベント + @Input を介して選択された項目を設定しても、追加のコードを実行する必要がある場合、DetailComponent はトリガーされません。したがって、これが許容できる解決策であるかどうかはわかりません。


しかし、これらの方法は両方とも、$rootScope.$broadcast または $scope.$parent.$broadcast を使用する Angular 1 の方法よりもはるかに複雑であるように見えます。

Angular 2 のすべてがコンポーネントであるため、コンポーネント通信に関する情報があまり提供されていないことに驚きます。

これを実現するための別の/より簡単な方法はありますか?

ベストアンサー1

rc.4に更新されました:Angular 2 の兄弟コンポーネント間でデータを受け渡そうとする場合、現時点で最も簡単な方法 (angular.rc.4) は、Angular2 の階層型依存性注入を利用して共有サービスを作成することです。

サービスは次のようになります:

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

@Injectable()
export class SharedService {
    dataArray: string[] = [];

    insertData(data: string){
        this.dataArray.unshift(data);
    }
}

さて、ここに親コンポーネントがあります

import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
    selector: 'parent-component',
    template: `
        <h1>Parent</h1>
        <div>
            <child-component></child-component>
            <child-sibling-component></child-sibling-component>
        </div>
    `,
    providers: [SharedService],
    directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{

} 

とその2人の子供

子供1

import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-component',
    template: `
        <h1>I am a child</h1>
        <div>
            <ul *ngFor="#data in data">
                <li>{{data}}</li>
            </ul>
        </div>
    `
})
export class ChildComponent implements OnInit{
    data: string[] = [];
    constructor(
        private _sharedService: SharedService) { }
    ngOnInit():any {
        this.data = this._sharedService.dataArray;
    }
}

子供2(兄弟)

import {Component} from 'angular2/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-sibling-component',
    template: `
        <h1>I am a child</h1>
        <input type="text" [(ngModel)]="data"/>
        <button (click)="addData()"></button>
    `
})
export class ChildSiblingComponent{
    data: string = 'Testing data';
    constructor(
        private _sharedService: SharedService){}
    addData(){
        this._sharedService.insertData(this.data);
        this.data = '';
    }
}

現在: この方法を使用する際に注意すべき点。

  1. 共有サービスのサービス プロバイダーのみを親コンポーネントに含め、子コンポーネントは含めないでください。
  2. コンストラクタをインクルードし、子にサービスをインポートする必要があります。
  3. この回答は、もともと初期の Angular 2 ベータ版向けに回答されたものです。変更されたのはインポート ステートメントだけなので、偶然に元のバージョンを使用した場合は、更新する必要があるのはそれだけです。

おすすめ記事