Jeff
Jeff

Reputation: 8431

access to the index of item in *ngFor

I have a loop in my html page. The code is:

<li *ngFor="let item of items" style="display: inline;">    
    <div class="col-lg-3 col-md-4 col-xs-6 thumb">
           <a class="thumbnail" [routerLink]="['/single-picture/:comment', {comment:item.index} ]">
                <img  [src]=item.images.low_resolution.url>
           </a>
    </div>       
</li>

In the line <a class="thumbnail" [routerLink]="['/single-picture/:comment', {comment:item.index} ]">

I want to pass the index of current item in the loop.

How can i do it?

Upvotes: 13

Views: 18166

Answers (2)

Mehari
Mehari

Reputation: 3267

Here is the syntax from the documentation:

Syntax

<li *ngFor="let item of items; let i = index">...</li>
<li template="ngFor let item of items; let i = index">...</li>
<template ngFor let-item [ngForOf]="items" let-i="index"><li>...</li></template>

Refer to the documentation here

For your case:

<li *ngFor="let item of items;let i=index" style="display: inline;">    
    <div class="col-lg-3 col-md-4 col-xs-6 thumb">
           <a class="thumbnail" [routerLink]="['/single-picture/:comment', {comment:item.index} ]">
                <img  [src]=item.images.low_resolution.url>
           </a>
    </div>       
</li>

Upvotes: 3

micronyks
micronyks

Reputation: 55443

<li *ngFor="let item of items;let i=index" style="display: inline;">      //<---added let i=index

    <div class="col-lg-3 col-md-4 col-xs-6 thumb">
       <a class="thumbnail" 
          [routerLink]="['/single-picture/:comment', {comment:i} ]">      //<-----changed this line 
           <img  [src]=item.images.low_resolution.url>
        </a>
    </div>  

</li>

Upvotes: 20

Related Questions