Allow more than one child component of the same type. Allow child components to be placed within the views of other custom components
How do Angular know which instance of "ToggleComponent" should be injected into each child component? It's always the parent one?
I have the same question as Bruno above. This part seems to be magic. How angular knows this?
it's the first time I see injecting a parent component through the constructor, i didn't even know it was possible, I thought only services could be injected, thank you!
Angular knows about the tree of components that are being rendered in your app. So it starts at the component that is trying to inject the ToggleComponent
and then walks up the tree until it finds the first instance of ToggleComponent
. This process is controlled by the ElementInjector
.
If it doesn't find a ToggleComponent
in the component tree, it will look for it in the providers
of the modules that are loaded.
If it still doesn't find it, Angular will throw an error. (You can avoid that error by adding @Optional()
where you inject it.)
For more detailed explanation, you can check out these two articles:
Fantastic! Thanks Isaac, this sounds really useful
I don't see where this pattern could be useful...the example is so contrived.
@gabriel This pattern basically let's you implement a pub-sub pattern where the parent component (publisher) doesn't need to know about the child components (subscribers). And the child components can be nested arbitrarily deep within the parent component.
Hi Isaac, what's the difference between the ToggleOnComponent and the ToggleOffComponent in regards the constructor? You do one toggle constructor injecting the ToggleComponent as private and the other toggle injecting as public, what's the reason behind that ? great course, Thank you!!! Oscar
@Oscar, good catch. They should both be public. They're both public in the code on Stackblitz.
private
injected objects can not be referenced in the template of the component. Since we're referencing the parent toggle.on
property in both templates, it should be public
.
I generally try to keep all injected dependencies private, unless they need to be public.
Hi Issac, thank you very much for the course,
qq - why are we using this.toggle.on inside toggle button and then send the value back to parent via setOnState? like this
setOnState() {
this.on = !this.on;
this.toggle.emit(this.on);
}
In this lesson I'm showing how to keep the state of the toggle in the parent toggle component. The button component needs to tell the parent component to update the state so all the other components can update.
@Isaac Thanks for the course. Should we use component constructor pattern instead of Input\Output pattern for sharing any information with child components. Thanks Ajay.