我试着按照这个答案,但它太混乱了
Angular 2 event catching between sibling components
子组件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上执行你想要的任何方法.或多或少这样的事情:
原文链接:https://www.f2er.com/angularjs/143798.htmlimport { 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); } }