如何在Angular 2中使用* ngFor在列表中打印json数组值? [英] How to print the json array values in a list using *ngFor in Angular 2?
问题描述
我有一个json数组,我想将值打印在一个简单的列表中.如何打印值?我必须遵循键值方法吗?我要添加我的Json数组结构和示例代码.它向我显示了错误.
I have a json array and i want to print the values in a simple list. How to print the values? Do I have to follow key value method? I'm adding my Json array structure and my sample code. It is showing me errors.
预期产量
*456
*123
or Arun :123
test:456
错误:
类型为对象"的"""[对象对象]". NgFor仅支持绑定到数组等Iterable.
"'[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
错误:找不到类型为对象"的其他支持对象"[对象对象]". NgFor仅支持绑定到Iterables,例如数组."
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
Json Array
{
"records": [{
"arun": [1, 2, 3],
"test": [4, 5, 6]
}]
}
**myTest.ts**
export class HomePageComponent extends AppComponent {
public bundle: any[];
ngOnInit(){
this.readArray();
}
readArray() {
this.bundle = {
"records": [{
"arun": [1, 2, 3],
"test": [4, 5, 6]
}]
}
console.log("array",this.bundle);
}
testComponent.html
<ul *ngFor="let det of bundle;">
<li>{{det.records}}</li>
</ul>
推荐答案
您需要在数组上使用ngFor,它应该是<div *ngFor="let record of bundle.records">
,并且您有嵌套的数组,可以使用以下命令访问项目
Object.keys
如演示中一样
You need to use ngFor over an array, it should be <div *ngFor="let record of bundle.records">
, also you have a nested array, you can access the items using
Object.keys
as in the demo
@Component({
selector: 'my-app',
template: `
<div *ngFor="let record of bundle.records">
<ul *ngFor="let key of objectKeys(record)">
<li>{{key}} :: {{record[key]}}</li>
</ul>
</div>
`,
})
DEMO
这篇关于如何在Angular 2中使用* ngFor在列表中打印json数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!