Search code examples
angularangular2-components

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?


Solution

  • 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>