Lea*_*Lea 13 json ngfor angular
我正在使用ngFor循环8个json对象,我不仅要循环值,还要计算循环值的数量并显示数字.
例如,如果json值为
Content:{
0:"Content1",
1:"Content2",
2:"Content3",
3:"Content4",
4:"Content5",
5:"Content6",
6:"Content7",
7:"Content8"
}
Run Code Online (Sandbox Code Playgroud)
我不仅要显示'内容'的循环值,还要计算它们,以便结果如下所示.
1 <- counting
Content1
2
Content2
3
Content3
4
Content4
5
Content5
6
Content6
7
Content7
8
Content8
Run Code Online (Sandbox Code Playgroud)
ald*_*ena 24
关于文档:https: //angular.io/guide/structural-directives#inside-ngfor和 https://angular.io/api/common/NgForOf
假设你有一个iterable:
let content = [
"Content1",
"Content2",
"Content3",
"Content4",
"Content5",
"Content6",
"Content7",
"Content8"
]
Run Code Online (Sandbox Code Playgroud)
然后你可以迭代和计数:
<li *ngFor="let item of content; let i = index">
{{i+1}} {{item}}
</li>
Run Code Online (Sandbox Code Playgroud)
如果要迭代对象而不是对象数组,请检查如何使用*ngFor迭代对象键
要记录,您需要一个自定义管道:
@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]);
}
}
Run Code Online (Sandbox Code Playgroud)
那就是
<li *ngFor="let key of objs | keys; let i = index"> ...
Run Code Online (Sandbox Code Playgroud)
从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>
Run Code Online (Sandbox Code Playgroud)
<ul>
<li *ngFor="let item of items; let i = index">
{{i}}. {{item}}
</li>
</ul>
{{items ? items.length : ''}}
Run Code Online (Sandbox Code Playgroud)
您可以只打印items数组的长度.
| 归档时间: |
|
| 查看次数: |
31227 次 |
| 最近记录: |