简体   繁体   中英

Angular - How to add a counter Variable from template to html property?

I have this HTML:

<ng-container *ngFor="let something of things; let i = index">
<span data-e2e="{{"abc" + i}}" class="checkmark"></span>
</ng-container>

I want to have this result rendered in the DOM:

<span data-e2e="abc0" class="checkmark"></span>
<span data-e2e="abc1" class="checkmark"></span>
...

But this {{"abc" + i}} wont work.

"abc" should be a string. How can I do this, without saving the property (counter: i) to the components controller

You should change,

<ng-container *ngFor="let something of things; let i = index">
<span data-e2e="{{"abc" + i}}" class="checkmark"></span>
</ng-container>

To:

<ng-container *ngFor="let something of things; let i = index">
<span [attr.data-e2e]="'abc'+i" class="checkmark"> {{something}} </span>
</ng-container>

Here you should use attr as prefix and need to assign the value to custom attribute using property binding like, [attr.data-e2e]="'abc'+i" ..

Working Stackblitz..

You should change:

<span data="normalString{{i}}" class="checkmark"></span>

normalString should be outside {{}}

also data attribute is not correct, read more how to properly add custom data attribute:

https://www.w3schools.com/tags/att_global_data.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM