Communicate between sibling components Angular 2

后端 未结 3 1300
我寻月下人不归
我寻月下人不归 2020-12-29 00:07

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

相关标签:
3条回答
  • 2020-12-29 00:20

    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);
    }
    
    0 讨论(0)
  • 2020-12-29 00:24

    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.

    0 讨论(0)
  • 2020-12-29 00:32

    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);
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题