Sandeep
Sandeep

Reputation: 33

Can we/How to access a grandchild component through @ViewChild in angular

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

Answers (2)

cs_pupil
cs_pupil

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:

  • To use @ViewChild like this, the child has to be in the view.
  • Angular 8+ may need: @ViewChild(ChildComponent, { static: false })
  • Similarly, you could bubble up the return value using @Output

Upvotes: 3

Qortex
Qortex

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

Related Questions