Communicate Between Two Related Components of Angular 2

I tried to execute this answer, but this is too confusing an Angular 2 event that captures between twin components

I want to call a method in child component 1 when something clicks on child component 2

Child component 2 emits an event called trackClick.

Parent component:

<div> <audio-player></audio-player> <audio-albums></audio-albums> </div> 

Child component 1 (audio player)

 // Don't know what to do here, want to call this function trackChanged(track){ console.log("YES!! " + track); } 

Child component 2 (audio albums)

 <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]); } 
+3
source share
3 answers

you cannot do it like that. you must first get child2 in the parent using @ViewChild (Child2) (it is important to select ViewChild by component not by line). then you need to catch the event in the parent and execute any method you want on child2. more or less 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); } } 
+6
source

Alternative (template only) method

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

The event handler references <audio-player> to the template variable #audioPlayer .

+3
source

Something like that:

Parent

 <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); } 
+1
source

Source: https://habr.com/ru/post/1258966/


All Articles