Access multiple viewchildren using @viewchild

Angular

Angular Problem Overview


I have created a custom component which i have placed in a for loop e.g

<div *ngFor="let view of views">

     <customcomponent></customcomponent>

</div>

The output of which will be:

<customcomponent></customcomponent>
<customcomponent></customcomponent>
<customcomponent></customcomponent>

I would like to know how i can get a reference to these components using @viewchild syntax or any other means when the number of these components can vary

when the component can be given a name e.g

<customcomponent #compID></customcomponent>

I can then reference it as follows:

@ViewChild('compID') test: CustomComponent

How do i reference it when this is not the case e.g using an index possibly?

(This question does not relate to using ElementRef as per other questions that have been previously asked as can be seen by the answers listed below) This question relates to the accessing multiple @ViewChild and using list queries.

Angular Solutions


Solution 1 - Angular

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
	<customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
	// print array of CustomComponent objects
	console.log(this.components.toArray());
}

l̶i̶v̶e̶ ̶d̶e̶m̶o̶

Solution 2 - Angular

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiotr StulinskiView Question on Stackoverflow
Solution 1 - AngularBeetleJuiceView Answer on Stackoverflow
Solution 2 - AngularsilentsodView Answer on Stackoverflow