10

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?

Stefan
  • 12,108
  • 5
  • 47
  • 66

4 Answers4

15

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>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
4

You can create one service which is shared between your child component in which you can define Observable so that you can subscribe to that Observable from one child and perform some action when you receive some value from another child. you can check https://stackoverflow.com/questions/39738974#39739184 which is used for parent to child communication but you can use same approach for child to child communication.

Community
  • 1
  • 1
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
1

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

Depends on what you consider as better ;).

There are some methods which runs, you just need to choose the flow of data which is more understandable and seems to work better for you.

For example you can use Service to communicate between those two Components. This is the way I do it, I implement all communication logic in Services, so my Components are only for presentation logic.

jmachnik
  • 1,120
  • 9
  • 19
0

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

You can perfectly tackle this problem with events, but these kind of problems tend to get easier if you use redux (or in angular2, ngrx/store). There are many good articles and videos about the subject, and while it might look a bit strange at first, it becomes very natural after a while.

Google around and watch some videos, its a very interesting way of working, and you'll also start to understand the role of rxjs and how it can help in your application.

Davy
  • 6,295
  • 5
  • 27
  • 38