角度ngFor索引

时间:2018-08-13 11:11:46

标签: angular typescript

我如何总是始终计算 viewable 输出(第一行,第二行,...)而不是数据(数据行1,数据行4,...)的索引? )? 因此,我想使其与ngIf而不是数据顺序相关。

data: number []=[0,1,2,10,2,37,4,9,11];


<ul *ngFor="let d of data; let i = index;">
  <ng-container *ngIf="d%2==0">
    <li>Index={{i}} Data={{d}}</li>
  </ng-container>
</ul>

https://stackblitz.com/edit/angular-u7u4ru

我想要输出

Index=0 Data=0
Index=1 Data=2
Index=2 Data=10
Index=3 Data=2
Index=4 Data=4

3 个答案:

答案 0 :(得分:1)

过滤组件中的数据

this.data.filter(x => {
      if (x % 2 == 0)
        return x;
    });

正在运行的演示https://stackblitz.com/edit/angular-feae8f

答案 1 :(得分:0)

在上一个生命周期事件:stackblitz

上使用带有钩的计数器和吸气剂
export class AppComponent  {
  name = 'Angular';
  data: number []=[0,1,2,10,2,37,4,9,11];
  count = 0;

  get counter() {
    return this.count++;
  }

  ngAfterContentChecked() {
    this.count = 0;
  }
}

答案 2 :(得分:0)

您应该在组件本身而不是模板中执行此操作。

使用.map()运算符修改数据:

this.data = [0,1,2,10,2,37,4,9,11].map(x => { 
    if(x%2 == 0)
        return x;
})
// Remove all empty values.
.filter(n=>!isNaN(n));

stackblitz

相关问题