14

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.

2
  • 1
    Take a look at this question. Commented Dec 22, 2017 at 1:38
  • Can we do this the other way around? Meaning, can we dynamically add a template reference variable to a dynamically created DOM element? Commented Oct 12, 2022 at 15:27

3 Answers 3

21

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;
Sign up to request clarification or add additional context in comments.

2 Comments

tried this, and it references just the first <li> element.
@amy8374 it certainly doesn't. ViewChild references single element. ViewChildren references multiple.
4

You can use like this code:

<ul>
    <li *ngFor="let item of items;let i = index;" #itemRef{{i}}>{{item.xyz}}</li>
</ul>

Look this question: enter link description here

1 Comment

@amy8374 It working,But you cannot use @ViewChild get it and must use @ViewChildren.
-6

You can use the index for it.

 <ul>
<li *ngFor="let link of links; let i=index;">
{{link.title}}{{i}} 
</li>
</ul>

1 Comment

i want to set the # not append to the text of <li>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.