访问* ngFor中的项目索引

时间:2016-08-12 06:11:51

标签: angular

我的html页面中有一个循环。代码是:

<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>

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

我想传递循环中当前项目的索引。

我该怎么做?

2 个答案:

答案 0 :(得分:11)

<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>

答案 1 :(得分:3)

以下是文档

中的语法
  

<强>语法

<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>

参考documentaion here

适合您的情况:

<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>