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?
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.
*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?
*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
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.
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With