Angular 2 Child1-Parent-Child2 event propagating

半城伤御伤魂 提交于 2019-12-25 05:32:23

问题


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?



来源:https://stackoverflow.com/questions/42286924/angular-2-child1-parent-child2-event-propagating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!