Communicate between sibling components Angular 2

醉酒当歌 提交于 2019-11-29 01:13:45

问题


I tried to follow this answer but its too confusing Angular 2 event catching between sibling components

I want to call a method in child component 1 when something is clicked on child component 2

Child component 2 emits an event called trackClick.

Parent Component:

<div>

    <audio-player></audio-player>

    <audio-albums></audio-albums>

</div>

Child Component 1 (audio-player)

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

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

Child Component 2 (audio-albums)

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

回答1:


you can't do it like this. first you have to get child2 in parent by using @ViewChild(Child2) (it's important to select ViewChild by component not by string). then you have to catch the event in parent and execute whatever method you want on child2. more or less something like this:

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);
  }

}



回答2:


An alternative (template-only way) is

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

The event handler references <audio-player> by the template variable #audioPlayer.




回答3:


Something like this:

Parent

<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);
}


来源:https://stackoverflow.com/questions/39132385/communicate-between-sibling-components-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!