Angular 2:ngFor index仅在满足条件时递增

时间:2017-07-19 19:01:08

标签: angular ngfor

我们说我有一系列我正在循环的对象:

arr = [ {a: 1}, {a: 2}, {a: 1} ]

我希望在视图中显示对象的索引,但我只想在满足条件时递增索引。像a == 1这样的东西。所以,如果我有一些代码,如:

<!-- I know this won't work -->
<ul>
  <li *ngFor="let obj of arr; let i = index">{{ i }}</li>
</ul>

...它会显示为:

<li>0</li>
<li></li>
<li>1</li>

1 个答案:

答案 0 :(得分:3)

app.component.ts:

arr:{a:number}[] = [{a: 1},{a: 2},{a: 1} ];

app.component.html

<ul>
  <div *ngFor="let obj of arr; let i = index"> 
    <div *ngIf="obj.a == 1">
    <li>{{i}}</li>
    </div>
  </div>  
</ul>