Reputation:
I came across a problem in which I need to have a unique id value for each data row I have inside my *ngFor
loop in angular 4.
My code goes like this:
<div *ngFor="let row of myDataList">
<div id="thisNeedsToBeUnique">{{ row.myValue }}</div>
</div>
Upvotes: 7
Views: 11963
Reputation: 41387
Use the index to generate unique id
<div *ngFor="let row of myDataList; let i = index">
<div [attr.id]="row.myValue + i">{{ row.myValue }}</div>
</div>
Upvotes: 5
Reputation: 619
Assuming that you have a unique id value inside your object, then you can do it like this:
<div *ngFor="let row of myDataList">
<div [attr.id]="row.myId">{{ row.myValue }}</div>
</div>
You can also do it like this:
<div *ngFor="let row of myDataList">
<div attr.id="{{row.myId}}">{{ row.myValue }}</div>
</div>
You can also concatinate a string and your dynamic value together like this:
<div *ngFor="let row of myDataList">
<div [attr.id]="'myString' + row.myId">{{ row.myValue }}</div>
</div>
<!-- Or -->
<div *ngFor="let row of myDataList">
<div attr.id="myString{{row.myId}}">{{ row.myValue }}</div>
</div>
Upvotes: 14