Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve all child components of a component in angular

Tags:

angular

I have an Angular Component and I need to get all the child components of this component. How can this be done?

like image 525
ILIA hu Avatar asked May 04 '18 16:05

ILIA hu


2 Answers

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

like image 177
Commercial Suicide Avatar answered Sep 17 '22 23:09

Commercial Suicide


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.

like image 45
diopside Avatar answered Sep 19 '22 23:09

diopside