92

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
  • 13,617
  • 16
  • 88
  • 129
Kim Wong
  • 2,027
  • 4
  • 17
  • 22

5 Answers5

152
<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>
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
19

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
  • 722
  • 1
  • 6
  • 18
9

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
  • 84,110
  • 37
  • 165
  • 215
Vipin Jain
  • 3,686
  • 16
  • 35
1

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>
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,636
  • 8
  • 29
  • 37
Norman Pilusa
  • 337
  • 2
  • 5