Creating a connection between two decoupled compon

2019-09-11 07:32发布

问题:

I am trying to find a way to create a connection between a component, and a child component that is completely decoupled.

For instance, if I have two components, parent-component, and child-component that will only ever exist inside parent-component in the markup, I need to find a way for parent-component and child-component to communicate both ways.

So for instance if I have the following markup:

<parent-component>
    <child-component></child-component>
    <child-component></child-component>
    <child-component></child-component>
    <child-component></child-component>
    <child-component></child-component>
</parent-component>

I need a way for the parent component to reference the state of each of the child components, and each of the child components to reference the state of the parent component.

Is there a way to do this in Angular 2? I've dug around everywhere, and I can't really find a solution.

回答1:

If you want a parent an child to communicate with one another the Angular2 recommendation is to use a service. This is covered in the cookbook : https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service