[Fixed] Angular how to loop throught QueryList with ViewChildren?

Issue

I have child components in ngFor :

@ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>;

Then i want to loop throught that QueryList :

console.log(this.singleMultiSelections) // 1 item in _results , but results are private
for(let component of this.singleMultiSelections){
  console.log(component); //Not Working
 }

Solution

There is nothing wrong with your code per se.

QueryList implements Iterable, so you can use methods such as forEach, map, and for (let i of items) on it. You can view this in more detail in the Angular Documentation.

Keep in mind that for the QueryList to produce the expected results, you can only call it after the LifeCycle hook AfterViewInit has been called. Until then the list will not have been loaded, you read the official notes.

You can do so like this:

@ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>;

onAfterViewInit() {
  for(let component of this.singleMultiSelections){
    // Code here
  }
}

Leave a Reply

(*) Required, Your email will not be published