13

Is there a way to dynamically set the #id, the HTML attribute that angular uses to construct the @ViewChild element reference?

Specific need: i have the following template, created by iterating through *ngFor, and i wanted to assign the Angular id on the iteration.

<ul>
   <li *ngFor="let link of links">
  </li>
</ul>

And after it gets interpreted, end up with something like:

<ul>
  <li #link1>
   </li>
  <li #link2>
   </li>
 </ul>

Now I know of many other ways to get the elements, i can assign the # to the ul element, etc, etc, but wondering on whether there is a way to do it on the ngFor.

EDIT AFTER SEEING THE ANSWERS AND TRYING OUT COMBINATIONS:

There doesn't seem to be a way to assign distinct local variable identifiers to the single elements generated by *ngFor. You can either get them all, like the accepted answer suggests, or just get the parent element, and find your way from there.

amy8374
  • 1,450
  • 3
  • 17
  • 26

3 Answers3

20

Despite the seeming resemblance between regular variables and #, multiple elements can be assigned to single local template reference variable:

<ul>
   <li *ngFor="let link of links" #linkRef></li>
</ul>

Which can be obtained with:

@ViewChildren('linkRef') linkRefs;
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 4
    @amy8374 it certainly [doesn't](http://plnkr.co/edit/cDEE2S3B27a3EvOrTfhH?p=preview). ViewChild references single element. ViewChildren references multiple. – Estus Flask Dec 22 '17 at 18:19