Angular 5 access divs list using @ViewChildren

As mentioned in this detailed answer, the valid selectors for ViewChildren include component types, directive types, and template reference variables. You cannot retrieve DOM elements with ViewChildren using CSS selectors like HTML element types (e.g. div) or class names.

One way to make it work in your case is to generate the div elements with an ngFor loop, and associate a template reference variable #divs to them:

<div #divs *ngFor="let item of [1,2]" [id]="'div-' + item">Div {{item}}</div>
<button (click)="getDivs()">Get divs</button>

You can then retrieve them in code with ViewChildren, using the template reference variable:

@ViewChildren("divs") divs: QueryList<ElementRef>;

getDivs() {
  this.divs.forEach((div: ElementRef) => console.log(div.nativeElement));
}

See this stackblitz for a demo.


I was able to achieve needed result by creating custom directive and querying it like this:

import { Directive, ElementRef, ViewChildren, Component, AfterViewInit, QueryList } from "@angular/core";

@Directive({selector: 'table th'})
export class DatatableHeadersDirective {
  nativeElement: HTMLTableHeaderCellElement = null;
  constructor(el: ElementRef) {
    this.nativeElement = el.nativeElement;
  }
}

@Component({
  selector: 'selctorname',
  templateUrl: 'htmlURL',
  styleUrls: ['styleURL'],
})
export class AwesomeDatatableComponent implements AfterViewInit {
  @ViewChildren(DatatableHeadersDirective) children: QueryList<DatatableHeadersDirective>;;

  ngAfterViewInit(){
    console.log(this.children.map(directive => directive.nativeElement))
  }
}