在同级组件Angular 2之间进行通信 [英] Communicate between sibling components Angular 2

查看:121
本文介绍了在同级组件Angular 2之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试遵循此答案,但是它太混乱了在两个同级组件

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

我想在子组件2

子组件2发出一个名为trackClick的事件.

Child component 2 emits an event called 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).那么您必须在parent中捕获事件并在child2上执行所需的任何方法.或多或少是这样的:

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

}

这篇关于在同级组件Angular 2之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆