【问题标题】:Angular 2: ngFor index only increment if case metAngular 2:ngFor 索引仅在遇到情况时才会增加
【发布时间】:2017-12-25 05:22:08
【问题描述】:

假设我有一个要循环的对象数组:

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>

【问题讨论】:

  • 您需要在组件中使用一个变量来手动和外部跟踪。如果需要/想要,可以提供示例。
  • 只需在包含条件增量的数组中的对象中添加一个属性,并在需要在组件中的函数内计算时计算进入该属性的值。 [ {a: 1, b: 0}, {a: 2}, {a: 1, b: 1} ]

标签: angular ngfor


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 2019-05-11
    • 1970-01-01
    • 2017-03-13
    • 2016-12-28
    • 2017-10-28
    • 2018-02-22
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多