angular

ngFor index in Angular

//IF YOU ARE USING ANGULAR > 2
<ul>
    <li *ngFor="let item of items; let i = index">
        {{i}} {{item}}
    </li>
</ul>

//IF YOU ARE USING ANGULAR = 1
<ul>
    <li *ngFor="#item of items; #i = index">
        {{i}} {{item}}
    </li>
</ul>
Output
*ngFor="#item of items; #i = index"

If you are looking to get index value inside '*ngFor', you can use this code snippet. As we know that when creating an Angular component we can add an HTML file that will be bind to the Angular models we are using in our component. Inside this we can use '*ngFor' to iterate through array and there is no perticular index provided inside this until we add some extra code to it.

If you are using Angular version > 2 you can use 'let i = index' along with *ngFor="let item of items" and the new syntax will be:

*ngFor="let item of items; let i = index"

If you are using older version of angular you can use below code syntax:

*ngFor="#item of items; #i = index"

For Older versions you can also use below code

<ul *ngFor="let item of items; index as i">
  <li>{{i}} {{item}}</li>
</ul>
Was this helpful?