Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access to the index of item in *ngFor

Tags:

angular

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?

like image 494
Jeff Avatar asked Aug 12 '16 06:08

Jeff


People also ask

How do I get the index of the current item in ngfor?

Here's how to get and print the index (or the iteration number) of the current item in an ngFor loop. In Angular, to get the index (or the iteration number) of the current item, add a second part to the ngFor expression (after a semi-colon) as shown here. Notice that I’m adding 1 to the output expression ( ndx+1 ) because the index is zero-based.

How to show Index in string interpolation with *ngfor?

*ngFor="let item of items; index as i;" // OR *ngFor="let item of items; let i = index;" // i will be the index, starting from 0 // and you can show it in the string interpolation with { { i }} Are there any code examples left?

What is the use of *ngfor in HTML?

*ngFor is an short hand form for ngForOf directive This can be used to iterate an array of objects or objects. Here is an ngFor syntax This can be applied to any html element objectarray - array of object object - typescript object or model class there are different local variables we can use index : get the index of an current item in an array

How to pass keyword to index in *ngfor loop?

keyword inside the *ngFor loop and then simply assign it with the index. For instance, . is the variable that we have defined. You can name it whatever you want such as The index value of the current item being iterated can also be passed to the ts file.


1 Answers

<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>
like image 144
Nikhil Shah Avatar answered Sep 25 '22 15:09

Nikhil Shah