在兄弟组件之间进行通信Angular 2

时间:2016-08-24 20:20:08

标签: angular eventemitter angular2-components

我试着按照这个答案但是太混乱了Angular 2 event catching between sibling components

子组件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]);
}

3 个答案:

答案 0 :(得分:7)

你不能这样做。首先,您必须使用@ViewChild(Child2)在父级中获取child2(按组件选择ViewChild非常重要)。然后你必须在父级中捕获事件并在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);
  }

}

答案 1 :(得分:5)

另一种选择(仅模板方式)

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

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

答案 2 :(得分:2)

这样的事情:

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

@ViewChild(Child2) child2Component: Child2Component;

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

Child1

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

CHILD2

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