Angular2 ngFor如何计算循环值的数量? [英] Angular2 ngFor how to count the number of looping values?

查看:676
本文介绍了Angular2 ngFor如何计算循环值的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ngFor循环8个json对象,我不仅希望循环这些值,而且还希望计算循环值的数量并显示该数字.

I am using ngFor to loop 8 json objects and I want not only to loop the values but also I want to count the number of looping values and display the number.

例如, 如果json值为

For example, if json value is

Content:{
0:"Content1",
1:"Content2",
2:"Content3",
3:"Content4",
4:"Content5",
5:"Content6",
6:"Content7",
7:"Content8"
}

我不仅要显示内容"的循环值,而且还希望对它们进行计数,以便结果如下所示.

I not only want to display looping values of 'Content', but I also want to count them so that the result could be this below.

1 <- counting
Content1

2
Content2

3
Content3

4
Content4

5
Content5

6
Content6

7
Content7

8
Content8

推荐答案

遍历数组

关于文档: https://angular.io/guide/structural-directives#inside-ngfor https://angular.io/api/common/NgForOf

Iterating over array

Regarding the docs: https://angular.io/guide/structural-directives#inside-ngfor and https://angular.io/api/common/NgForOf

假设您有一个迭代过程:

Say you have an iterable:

let content = [
  "Content1",
  "Content2",
  "Content3",
  "Content4",
  "Content5",
  "Content6",
  "Content7",
  "Content8"
]

然后您可以使用以下方法进行迭代和计数:

Then you can iterate and count with:

<li *ngFor="let item of content; let i = index">
    {{i+1}} {{item}}
</li>

遍历对象属性

如果要遍历对象而不是对象数组,请检查为进行记录,您需要一个自定义管道:

For the record, you need a custom pipe:

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)//.map(key => value[key]);
    }
}

所以应该是

<li *ngFor="let key of objs | keys; let i = index"> ...

更新

从Angular 6.1+开始,您可以使用本机KeyValuePipe.

https://angular.io/api/common/KeyValuePipe

作记录:

<li *ngFor="let item of data | keyvalue; let i = index">
  {{i+1}}. {{item.key}} - {{item.value}}
</li>

这篇关于Angular2 ngFor如何计算循环值的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆