How to set dynamic id in *ngFor?

121,179

Solution 1

<div class = "CirclePoint" *ngFor="let c of circles" 
    [attr.id]="'Location' + c.id">
</div>

<div class = "CirclePoint" *ngFor="let c of circles" 
    attr.id="Location{{c.id}}">
</div>

Solution 2

This also will work:

<div class = "CirclePoint" *ngFor="let c of circles">
   <div [id]="c.id"></div>
</div>

If you want to add a prefix, say "loc";

<div class = "CirclePoint" *ngFor="let c of circles">
   <div [id]="'loc' + c.id"></div>
</div>

Using [] helps to add values dynamically.

Solution 3

Try this:

 <div class = "CirclePoint" *ngFor="let c of circles">
     <div id="location_{{c.id}}">write something which you want like c.x </div>
 </div>`

Hopefully this will work for you. I searched StackOverflow and I found this answer.

Share:
121,179

Related videos on Youtube

Kim Wong
Author by

Kim Wong

I can do this all day.

Updated on March 14, 2022

Comments

  • Kim Wong
    Kim Wong about 2 years

    How to set dynamic id in Angular 2?

    I have tried:

    <div class = "CirclePoint" *ngFor="#c of circles" id = "{{ 'Location' + c.id }}"></div>
    
    this.circles = [
            { x: 50 , y: 50 ,id : "oyut1" },
            { x: 100 , y: 100 ,id : "oyut3"  },
            { x: 150 , y: 150 ,id : "oyut2"  }
    ];
    

    but it does not work.

  • Kim Wong
    Kim Wong over 8 years
    Thank you for your answer. But i am working on angular2 "ng-attr-id" doesn't work anymore.
  • Vipin Jain
    Vipin Jain over 8 years
    sorry i don't work in angular2 without see tag, I response you.I found some answer from net
  • Günter Zöchbauer
    Günter Zöchbauer over 8 years
    Thanks for the feedback, I thought there were a few common attributes with special treatment but maybe I mixed something up.