Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular viewChild for dynamic elements inside ngFor

My template has something like this:

<div *ngFor="let data of array">
    <div #div></div>
</div>

is there a way for me to name each div differently using the #? And if so, how can I access them later in my TS file?

by the way, what are these # called? I cant search for them since I have now idea what these are (I just know what they're used for)

like image 628
Gustavo Berwanger Avatar asked Jul 09 '18 19:07

Gustavo Berwanger


2 Answers

TL;DR Use ViewChildren instead of ViewChild

As @Commerical Suicide mentioned you cannot set the references dynamically.

The #div is called template reference variable.

You can access your divs via ViewChildren in you *.ts file.

Sample: @ViewChildren('div') divs: QueryList<ElementRef>

Then you can call multiple methods on your new QueryList, like forEach or find.

like image 158
Batajus Avatar answered Oct 16 '22 20:10

Batajus


There is an alternative way to catch and handle dynamic elements inside the loop by events.

<div *ngFor="let name of names">
  <input #boofoo type="text" (click)="onClick($event, name)" />
  <button (click)="boofoo.click()">Change text</button>
</div>

See example stackblitz

like image 40
Vassilis Blazos Avatar answered Oct 16 '22 18:10

Vassilis Blazos