如何在 * ngFor 中设置动态 id?

如何设置角度2的动态 id

我试过了:

<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"  }
];

但是没有用。

133504 次浏览

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.

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

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>

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.

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>