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?
问题:
回答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
).
回答2:
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?