83

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.

Alexander Abakumov
  • 12,301
  • 14
  • 79
  • 125
Kim Wong
  • 1,857
  • 3
  • 15
  • 22

5 Answers5

141
<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>
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
13

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.

Neenu Chandran
  • 640
  • 1
  • 6
  • 17
7

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.

Pardeep Jain
  • 78,495
  • 36
  • 155
  • 210
Vipin Jain
  • 3,553
  • 15
  • 34
0

Inside the component tag instead of the usual id="#c" use [id]="#c". This also applies to dynamic class names. See example below:

<div class = "CirlePoit" *ngFor="#c of circles" [id] = "#c"> </div>
Nissa
  • 4,598
  • 8
  • 29
  • 37
Norman Pilusa
  • 337
  • 2
  • 5
0

INDEX CAN BE USED AS DYNAMIC ID

<div class="test" *ngFor="let item of data; let i = index">
<div class="function_div" (click)="test(i);">Test Button </div>
    {{item}}
</div>