[Solved] ngFor with index as the value in the attribute

Article Mohaimen Khalid

Problem:

I have a simple ngFor Loop, it also tracks the current index. I want to index The value is stored in the attribute so that I can print it. But I can't figure out how it works. I want to data-index storage #i Value.

I tried several methods. But none of them are worked.

Solutions:

Angular version 1
<ul>
    <li *ngFor="#item of items; #i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>
Angular Version >= 2

You have to use let To declare the value instead#

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>
Angular version 5/6/7/8
<ul>
    <li *ngFor="let item of items; index as i">
        {{i+1}} {{item}}
    </li>
</ul>

Hope it will work.