Search code examples
angularngfor

ngFor with index as value in attribute


I have a simple ngFor loop which also keeps track of the current index. I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I basically have this:

<ul *ngFor="#item of items; #i = index" data-index="#i">
    <li>{{item}}</li>
</ul>

I want to store the value of #i in the attribute data-index. I tried several methods but none of them worked.

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

How can I store the index value in the data-index attribute?


Solution

  • In Angular Version 17+ using built in control flow:

    <ul>
      @for (item of items; track item; let  i = $index) {    
        <li>
            {{i+1}} {{item}}
        </li>
        }
    </ul>
    

    In Angular Version 5+:

    <ul>
      <li *ngFor="let item of items; index as i">
        {{i+1}} {{item}}
      </li>
    </ul>
    

    I would use this syntax to set the index value into an attribute of the HTML element:

    Angular 2-4

    You have to use let to declare the value rather than #.

    <ul>
        <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
            {{item}}
        </li>
    </ul>
    

    AngularJS

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

    Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.