简体   繁体   English

在angular2模板ngFor中声明计数变量

[英]Declaring a counting variable in angular2 template ngFor

Suppose I have an array of data as follows. 假设我有一个数据数组如下。

datas : [
  {
    nums : [121,222,124,422,521,6312,7141,812]
  },{
    nums : [121,222,124,422,521,6312,7141,812]
  },{
    nums : [121,222,124,422,521,6312,7141,812]
  }
]
nums = [121,222,124,422,521,6312,7141,812]

I wanted to display the even numbers in the array after a serial number like shown below. 我想在序列号之后显示数组中的偶数,如下所示。

1. 222
2. 124
3. 422
4. 6312
5. 812
6. 222
7. 124
8. 422
9. 6312
10. 812
11. 222
12. 124
13. 422
14. 6312
15. 812

But I could not figure out a way to set the indexes after the "even" check. 但我无法想出在“偶数”检查后设置索引的方法。 Currently, I display the texts using the following code. 目前,我使用以下代码显示文本。

<div *ngFor="let data of datas">
  <div *ngFor="let num of data.nums; let rowIndex = index">
    <div *ngIf="num % 2 == 0">
      {{rowIndex+1}}. {{num}}
    </div>
  </div>
</div>

But it displays 但它显示出来

2. 222
3. 124
4. 422
6. 6312
8. 812
2. 222
3. 124
4. 422
6. 6312
8. 812
2. 222
3. 124
4. 422
6. 6312
8. 812

Is there a way to set a counter that increments every time the ngIf condition is validated so that I can display with the correct indexes. 有没有办法设置一个计数器,每次验证ngIf条件时递增计数器,以便我可以显示正确的索引。

You should use a pipe to filter the *ngFor . 您应该使用管道来过滤*ngFor See https://angular.io/docs/ts/latest/guide/pipes.html ("Flying Heroes pipe") which gives a good example for that. 请参阅https://angular.io/docs/ts/latest/guide/pipes.html("Flying Heroes pipe“),它为此提供了一个很好的示例。

<div *ngFor="let num of (nums | evenNums); let rowIndex=index">
  {{rowIndex+1}}. {{num}}
</div>

and

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'evenNums' })
export class EvenNumsPipe implements PipeTransform {
  transform(allNums: number[]) {
    return allNums.filter(num => num % 2 == 0);
  }
}

Also compare How to apply filters to *ngFor 还要比较如何将过滤器应用于* ngFor

Update: As far as I understand all you'd have to do is 更新:据我所知,你所要做的就是

<div *ngFor="let data of datas">
  <div *ngFor="let num of (data.nums | evenNums); let rowIndex = index">
      {{rowIndex+1}}. {{num}}
  </div>
</div>

The pipe should just filter the nums the same way, doesn't matter if it's inside a nested for or whatever. 管道应该以相同的方式过滤nums,如果它在嵌套for或其他内容中无关紧要。

Update 2: I have created a Plunkr to do this: https://plnkr.co/edit/NwoDPZqukKM7RyCHJudu?p=preview Seems like there is no other way than having a custom function that counts the rows so far. 更新2:我创建了一个Plunkr来执行此操作: https ://plnkr.co/edit/NwoDPZqukKM7RyCHJudu?p = preview似乎除了拥有一个自定义函数到目前为止计算行之外别无他法。 Angular does not support having a custom increment on a counter. Angular不支持在计数器上具有自定义增量。 I guess this is due to the guideline that there should be as minimal logic as possible in the templates. 我想这是由于指南在模板中应该尽可能少的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM