问题
I have the following markup to display any component within a lightbox:
<lightbox>
<some-comp></some-comp>
</lightbox>
I am trying to find the more generic and Angular way for both components to communicate (I have read https://angular.io/guide/component-interaction). For instance, the child component might say to the lightbox:
- My content is large so you need to expand.
- I contain a form and here is the data submitted via the form.
- Etc.
IMPORTANT. The lightbox doesn't know in advance which type of component it will hold.
I can make it work by injecting a service in both components and the service contains a Subject
that serves as a communication bus between the two components (this solution is described in the docs).
But is there another way? I am developing a UI component library and the service solution forces the users of the library to inject and manipulate a service in every component they display in the lightbox. I'd like to avoid that.
(Another idea that I had was for the lightbox to gain access to its child component and subscribe to a specific property on that component, but it's hard to do in a generic manner.)
回答1:
pass child to parent explicitly
One way would be to pass the child explicitly
<parent [child]="child">
<child #child></child>
</parent>
Plunker example
provide a service on the parent
An alternative way is to provide a service on the parent, and inject it in the child component.
Plunker example
It is better to use observables (BehaviorSubject
, ...) for communication instead of the simple field approach used in the Plunker.
conclusion
In every way, there is some cooperation required, either from the developer who uses the parent component, or the developer who builds supported child components.
回答2:
Taking Forward Gunter's answer you can also look at NGRX.
It's one of the best ways to communicate between large components and both the components will acts like Dumb Components
i:e will not have any idea of the type of data each will hold.
Keeping the data at a central location will also help you manage state of the application well which will lead to better flexibility and ability to add future enhancements.
I have a full page dedicated to ngrx(v4) hope it helps link
来源:https://stackoverflow.com/questions/46014977/communication-between-a-lightbox-component-and-its-child-component