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.
You can declare variables in html code by using a template element in Angular 2 or ng-template in Angular 4+. Templates have a context object whose properties can be assigned to variables using let binding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.
In the template, you use the hash symbol, # , to declare a template variable. The following template variable, #phone , declares a phone variable with the <input> element as its value. Refer to a template variable anywhere in the component's template.
Instead of two-way binding, we can easily fetch a value of any input through local references in Angular. Local references can be fetched directly from the component template and into the component typescript class. Lets check out how do we use local references.
To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName . In the code below, a template reference variable is created that references the <div> with id test-div .
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With