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.
<!-- It does't work --> <div *ngFor="let item of items; let i = index"> <div #item{{i}}></div> </div>
Contents
Use @ViewChildren
Of course, Angular has the solution of that problem.
It can get elements with the following.
<div *ngFor="let item of items; let i = index"> <div #items></div> </div>
And use ViewChildren in ts.
export class Page { @ViewChildren('items') items: QueryList; }
Although the items property is type of QueryList, you can arraylize property from type of QueryList as the following.
export class Page { @ViewChildren('items') items: QueryList; ngOnInit() { this.items.toArray() } }
Discussion
New Comments
No comments yet. Be the first one!