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

前端之家收集整理的这篇文章主要介绍了在兄弟组件Angular 2之间进行通信前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试着按照这个答案,但它太混乱了 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]);
}
你不能这样做.首先,您必须使用@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);
  }

}

猜你在找的Angularjs相关文章