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


70

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

但它不起作用。

Answers:


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


感谢您的反馈,我认为有一些共同的属性可以接受特殊待遇,但也许我将一些东西混在一起了。
君特Zöchbauer

5

这也将起作用:

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

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


4

尝试这个:

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

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


谢谢您的回答。但是我正在使用angular2“ ng-attr-id”不再工作。
Kim Wong

抱歉,我在没有看到标签的情况下不在angular2中工作,我回复了你。我从网上找到了一些答案
Vipin Jain

0

在component标签内,而不是通常的id="#c"用法[id]="#c"。这也适用于动态类名。请参见下面的示例:

<div class = "CirlePoit" *ngFor="#c of circles" [id] = "#c"> </div>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.