2016-08-24 66 views
3

我想按照這個答案,但它太混亂Angular 2 event catching between sibling components同級組件Anguar之間的溝通2

我想調用一個方法子組件1當點擊子組件的東西2

子組件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]); 
} 

回答

6

你不能這樣做。首先必須通過使用@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); 
    } 

} 
+1

好吧,我很害怕它必須是child2-> parent-> child1,謝謝虐待 –

1

事情是這樣的:

家長

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

一種替代(僅模板路)是

<audio-player #audioPlayer></audio-player> 
<audio-albums (trackClick)="audioPlayer.trackChanged($event)"></audio-albums> 

事件處理程序由模板變量#audioPlayer<audio-player>引用。

+1

哦,這很好,而不是通過父母......謝謝! –