Rizwan
Rizwan

Reputation: 4433

how to used index with *ngFor in angular 2, 4, 5

if you are using angular 2, 4/5** you can't used $index directly, for using index you need to define first

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

{{i}} is the index of items

but in angular 1.x you can used index like this:

<li ng-repeat="let item of items>{{item}} - {{$index}}</li>

Upvotes: 1

Views: 68

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176886

if you are using angular 2+ then you should do like this for getting index , so in angular 2 onwards you don't have ng-repeat it replaced by *ngFor

<li *ngFor="let user of userObservable | async as users; 
                         index as i; ">
   {{i}}/{{users.length}}. {{user}}
</li>

or

<li *ngFor="let user of userObservable | async as users; 
                         let i = index; ">
   {{i}}/{{users.length}}. {{user}}
</li>

From the doc : NgForOf

Upvotes: 2

Related Questions