I have an Angular Component and I need to get all the child components of this component. How can this be done?
One of possible solutions (may be there is a better one), is to use ViewChildren
, and this way you will get the access to all child components with specified name:
export class YourComponent {
@ViewChildren(ChildComponentFoo) private _childrenFoo: QueryList<ChildComponentFoo>;
@ViewChildren(ChildComponentBar) private _childrenBar: QueryList<ChildComponentBar>;
/* ... */
}
Here is an example: STACKBLITZ
The previously-posted solution with ViewChildren will do the trick if you individually import and name each Component you want to query. An alternative, if you don't want to be concerned with what specific type the component is, is to give the same template variable to each component you eventually want to access.
<component1 #disabler></component1>
<component2 #disabler></component2>
<component3 #disabler></component3>
Then you can use ViewChildren and QueryList with type any
@ViewChildren('disabler') mycomponents: QueryList<any>;
You could also use contentchildren if the components are transcluded
@ContentChildren('disabler') mycomponents: QueryList<any>;
From here there are several approaches, but I would just give each of these components an identically named method that disables them.
this.mycomponents.forEach((element)=>{
element.disable();
})
They don't necessarily all have to have the same method with the same name, it just makes it simpler to iterate through them all programmatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With