如何在 Angular 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" }
];
但它不起作用。
<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>
这也行得通:
<div class = "CirclePoint" *ngFor="let c of circles">
<div [id]="c.id"></div>
</div>
如果您想添加前缀,请说“loc”;
<div class = "CirclePoint" *ngFor="let c of circles">
<div [id]="'loc' + c.id"></div>
</div>
使用 [] 有助于动态添加值。
试试这个:
<div class = "CirclePoint" *ngFor="let c of circles">
<div id="location_{{c.id}}">write something which you want like c.x </div>
</div>`
希望这对您有用。我搜索了 StackOverflow,找到了这个答案。
索引可以用作动态ID
<div class="test" *ngFor="let item of data; let i = index">
<div id="i" class="function_div" (click)="test(i);">Test Button </div>
{{item}}
</div>
在组件标签内使用
id="#c"
,而不是通常的 [id]="#c"
。这也适用于动态类名。请参阅下面的示例:
<div class = "CirlePoit" *ngFor="#c of circles" [id] = "#c"> </div>