Angular – Get elements in ngFor with @ViewChildren

I tried to get elements that were rendered with “ngFor" loop, with putting reference variables to them for example, “#name1", “#name2". But it couldn’t work as the following.

  1. <!-- It does't work -->
  2. <div *ngFor="let item of items; let i = index">
  3. <div #item{{i}}></div>
  4. </div>

Use @ViewChildren

Of course, Angular has the solution of that problem.
It can get elements with the following.

  1. <div *ngFor="let item of items; let i = index">
  2. <div #items></div>
  3. </div>

And use ViewChildren in ts.

  1. export class Page {
  2. @ViewChildren('items') items: QueryList;
  3. }

Although the items property is type of QueryList, you can arraylize property from type of QueryList as the following.

  1. export class Page {
  2. @ViewChildren('items') items: QueryList;
  3. ngOnInit() {
  4. this.items.toArray()
  5. }
  6. }