Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: setting the local variable # dynamically

Tags:

angular

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.

like image 476
amy8374 Avatar asked Dec 21 '17 23:12

amy8374


People also ask

How do I declare a variable in Angular 4?

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.

How do you declare a variable in Angular 12?

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.

What is local reference in Angular?

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.

How do I declare a template reference variable in component?

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 .


2 Answers

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;
like image 191
Estus Flask Avatar answered Sep 28 '22 05:09

Estus Flask


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

like image 39
Wang Xiao Avatar answered Sep 28 '22 05:09

Wang Xiao