How to set dynamic id in *ngFor?

AngularIonic2

Angular Problem Overview


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.

Angular Solutions


Solution 1 - Angular

<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 - Angular

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 - Angular

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.

Solution 4 - Angular

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>

Solution 5 - Angular

> 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKim WongView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularNeenu ChandranView Answer on Stackoverflow
Solution 3 - AngularVipin JainView Answer on Stackoverflow
Solution 4 - AngularNorman PilusaView Answer on Stackoverflow
Solution 5 - AngularNadeeshan HerathView Answer on Stackoverflow