我试着按照这个答案,但它太混乱了
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上执行你想要的任何方法.或多或少这样的事情:
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); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。