兄弟组件之间的通信 Angular 2

Communicate between sibling components Angular 2

我试图遵循这个答案,但它太混乱了

当点击 子组件 2 时,我想在 子组件 1 中调用一个方法

子组件 2 发出一个名为 trackClick 的事件。

父组件:

<div>

    <audio-player></audio-player>

    <audio-albums></audio-albums>

</div>

子组件 1(音频播放器)

// Don't know what to do here, want to call this function

trackChanged(track){
    console.log("YES!! " + track);
}

子组件 2(音频专辑)

<li class="track" (click)="playTrack(track)"> </li>

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

playTrack(track):void{
    console.log("calling playTrack from child 2:" + track);  
    this.trackClick.next([track]);
}

你不能这样做。首先,您必须使用 @ViewChild(Child2) 在父级中获取 child2(对于 select ViewChild 按组件而不是按字符串很重要)。然后你必须在 parent 中捕获事件并在 child2 上执行你想要的任何方法。或多或少是这样的:

import { AudioAlbumsComponent }  from '...';
import { AudioPlayerComponent }  from '...';

@Component({ 
  template: `
    <div>
      <audio-player></audio-player>
      <audio-albums (trackClick)="onTrackClicked($event)"></audio-albums>
    </div>`,
  directives: [AudioPlayerComponent, AudioAlbumsComponent],
}) 

export class Parent {
  @ViewChild(AudioPlayerComponent) private audioPlayer: AudioPlayerComponent;

  onTrackClicked($event) {
    this.audioPlayer.trackChanged($event);
  }

}

像这样:

Parent

<div>
    <audio-player (trackchanged)="trackChanged($event);></audio-player>
    <audio-albums></audio-albums>
</div>

@ViewChild(Child2) child2Component: Child2Component;

trackChanged(value:any) {
 child2Component.trackChanged(value);
}

孩子 1

...
@Output() trackchanged= new EventEmitter();
...
playTrack() {
    this.trackchanged.emit({value: this.track});
}

孩子 2

trackChanged(track){
    console.log("YES!! " + track);
}

另一种(仅模板方式)是

<audio-player #audioPlayer></audio-player>
<audio-albums (trackClick)="audioPlayer.trackChanged($event)"></audio-albums>

事件处理程序通过模板变量 #audioPlayer 引用 <audio-player>