Accessing a Component’s Grandchildren in Angular
Let’s say we have three components: grandparent component 👴🏻, parent component 👩🏻 and a child component 👶🏻 .
I want to access the child component from the grandparent component.
Your first instinct would probably be to use @ViewChildren
and do the following:
The Problem
Unfortunately, using @ViewChildren
from grandparent component to query the child component won’t work.
According to Angular’s documentation on @ViewChildren
:
You can use ViewChildren to get the
QueryList
of elements or directives from the view DOM
Since the child is wrapped by the parent he won’t be in the grandparent’s view DOM, therefore he won’t be available for querying.
Don’t worry we can still accomplish that, we just have to work a bit harder 💪🏻
The Solution
The first thing we need to do is query all the child components from the parent component:
And the parent components from the grandparent component:
Since the @ViewChildren
decorator gives you access to the component’s instance we could call showChildName()
directly from the grandparent! 🎉
Now let’s put it all together:
My Use Case
I came across this problem at work (Datorama ❤️) when I needed to create a list with keyboard navigation that contained groups and items.
I wanted to use Angular Material’s FocusKeyManager
to manage the navigation over the list’s items.
Since the FocusKeyManager
needs a QueryList
of the list’s items, I needed a way to query them straight from the container component.
Final Words
Of course, you can take this concept into much more complex regions like querying multiple parents and creating a new flat QueryList
which contains all the children and etc… but you get the point.