82

如何id在 Angular 2 中设置动态?

我努力了:

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

但它不起作用。

4

5 回答 5

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

对于id属性,这可能也有效(我自己还没有尝试过)

<div class = "CirclePoint" *ngFor="let c of circles" 
[id]="'Location' + c.id">
</div>

于 2016-01-02T21:47:34.843 回答
12

这也将起作用:

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

使用 [] 有助于动态添加值。

于 2019-09-16T07:21:10.523 回答
6

尝试这个:

 <div class = "CirclePoint" *ngFor="let c of circles">
     <div id="location_{{c.id}}">write something which you want like c.x </div>
 </div>`

希望这对你有用。我搜索了 StackOverflow 并找到了这个答案

于 2016-01-02T17:25:23.687 回答
0

里面的组件标签而不是通常id="#c"使用的[id]="#c". 这也适用于动态类名。请参见下面的示例:

<div class = "CirlePoit" *ngFor="#c of circles" [id] = "#c"> </div>
于 2017-10-31T19:16:20.147 回答
0

INDEX 可用作动态 ID

<div class="test" *ngFor="let item of data; let i = index">
<div class="function_div" (click)="test(i);">Test Button </div>
    {{item}}
</div>
于 2021-03-17T19:58:14.657 回答