31
votes

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)

1
Pity, but it's impossible to name these references dynamically, so you can't do something like #div{{i}}.Commercial Suicide
They are called template reference variables - angular.io/guide/template-syntax#ref-varsWand Maker
Can you tell us more about why you need to name them dynamically and what's your final goal?maxime1992
these divs will be filled with Konva images after an image submit, but I need to get their size whenever I resize my window (which I did using window:resize), create them or do some other stuff like minimizing/maximizing the window, which I beieve can be done through events and having references to them using viewChildGustavo Berwanger

1 Answers

44
votes

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.