Angular › Template Reference Variables & ViewChild

How would you use ViewChildren to get references to multiple instances of the same child component or element?

Advanced

Answer

ViewChildren returns a QueryList containing every matching element or component instance found in the parent's template, which you can iterate over like an array, and it automatically updates if the number of matching elements changes over time, such as items being added or removed from a list.
@ViewChildren(ItemComponent) items!: QueryList<ItemComponent>;

ngAfterViewInit() {
  this.items.forEach((item) => console.log(item));
  this.items.changes.subscribe(() => console.log('The list of items changed'));
}
Real-world example A form with a dynamic number of input components uses ViewChildren to loop through every current input instance and validate them all together, automatically staying in sync even as inputs are added or removed.

Common follow-ups: What does the changes observable on a QueryList actually emit, and when does it fire?;How does ViewChildren differ from ContentChildren?