0

I am working on Angular 2 for only couple of weeks, so try to be considerate, please, and maybe give me some useful advice? Thank you. I have a main component(pageComponent), that inside its template has other two smaller components(tableComponent and filterComponent), each with its own functions and properties. How do I catch an event created in one of the child components and propagate it to another child component of the same parent? In other words, how to propagate and communicate events between two sibling components within the same parent component's template?

Garth Mason
  • 7,611
  • 3
  • 30
  • 39
Vladimir Despotovic
  • 3,200
  • 2
  • 30
  • 58

2 Answers2

1

I think you've got a couple of options here.

The first child component could emit the event using the @Ouput decorator, and have that event handler invoke an action on the sibling.

E.g. the sibling components

export class TableComponent {
@Output() anEvent: EventEmitter<any> = new EventEmitter<any>();
..
}

export class FilterComponent {

    callMeWhenSomethingHappens($event){
     ..
    }
}

The parent component template, which uses the #theFilter local variable to call the filter component when the event is emitted.

<app-filter #theFilter>
</app-filter>

<app-table (anEvent)="theFilter.callMeWhenSomethingHappens($event)">
</app-table>

You could also look at using a shared service if the sibling components don't have access to each other in the template (e.g. if they are created by a router-outlet).

Garth Mason
  • 7,611
  • 3
  • 30
  • 39
1

You can use the Flux pattern. Basically have your components subscribe to events exposed from your service. Since services are singletons, you can share the data that it provides across components, no matter how deep they are in the component tree. Here is an example: How can I maintain the state of dialog box with progress all over my Angular 2 application?

enter image description here

Community
  • 1
  • 1
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • Ok, I don't need a service to propagate to two components. I need one coponent to propagate its event to another component, from the same parent component (meaning that the parent component has two insertion points and the two child components are inserted there, using each their own selector). – Vladimir Despotovic Feb 17 '17 at 14:21
  • 1
    Sibling components shouldn't talk to each other directly. That creates a coupling between the component and it's parent, and between the component and its sibling. Over time, this pattern is difficult to maintain. A better pattern is to propagate data in one direction: component --> event --> service --> propagate to subscribed components – Michael Kang Feb 17 '17 at 14:41