Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 components: child to child communication

I have three components in an Angular 2 app: C0, C1 and C2. The first one (C0) represents an html template, having multiple child components (ui elements). Now, if someone clicks on a button in C1 (menu), how may I notify C2 (calendar) about that?

enter image description here

I tried some examples from the component communication page from the angular site. I ended up with an approach, where I took an EventEmitter at C1, to notify the parent C0. And then used a setter to notify C2.

This works, but seems very messy, even for a hand full of events. This cant be the solution, if my app might have hundreds of events in the end.

Is there a better way, to handle such kind of communication?

like image 315
Stefan Avatar asked Oct 17 '16 12:10

Stefan


People also ask

How do you call a child component method in parent component in Angular 2?

When user focus on ParentComponent's input element, you want to call ChildComponent's doSomething() method. Simply do this: Give app-child selector in parent. component.

How do you implement communication between child to parent element in Angular?

Configuring the child componentlinkThe EventEmitter then relays the data to the parent component. Import Output and EventEmitter in the child component class: content_copy import { Output, EventEmitter } from '@angular/core'; In the component class, decorate a property with @Output() .


1 Answers

I think you should add an EventEmitter to C1 as you mentioned.
You can bind to a method on C2 without involving C0 by adding a template variable to C2 and refer to it using it like:

<c1 (customEvent)="c2.onClick($event)"></c1>
<c2 #c2></c2>
like image 146
Günter Zöchbauer Avatar answered Sep 20 '22 13:09

Günter Zöchbauer