我试着按照这个答案但是太混乱了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]);
}
答案 0 :(得分:7)
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);
}