Reputation: 33
I have a Component, ChildComponent and a GrandChildComponent. I want the Component to listen to an event emitted by the GrandChildComponent in ngViewAfterInit of the Component. But my GrandChildComponent is not accessible from Component, when I try to access the GrandChildComponent through @ViewChild. Is it not possible or is there any alternate way to implement this?
Upvotes: 3
Views: 6854
Reputation: 3062
Since you can call a child's function, you can have the child call the grandchild's function. Not sure if it's the best idea, but it's possible.
Parent:
@ViewChild(ChildComponent) child!: ChildComponent;
makeGrandchildDoSomething() {
this.child.callChild();
}
Child:
@ViewChild(GrandchildComponent) grandchild!: GrandchildComponent;
callChild() {
this.grandchild.doSomething();
}
Grandchild:
doSomething() {
//grandchild special function
}
Notes:
@ViewChild
like this, the child has to be in the view.@ViewChild(ChildComponent, { static: false })
@Output
Upvotes: 3
Reputation: 7466
What you really need is inter-components interaction.
One way would be to hack your way around as you suggest and have the grandchild somehow get the event, but it would be cumbersome. And then what if for design reasons you want to change the relationship between your communicating components?
The idiomatic way to go is rather to have the components share information whatever their relationships in the templates.
Angular docs describe this very well in this section of this page (take a look at the whole page to have a better grasp at what I just explained).
Upvotes: 0