我有一个 JSON 对象,它具有多个级别的嵌套对象以及嵌套的对象数组。我想知道如何使用 Angular2 和 *ngFor 迭代对象并最终打印出列出的内容。第一个 *ngFor 有效,但下一个 *ngFor 给我错误提示Cannot read property nodes of undefined
当前 HTML 代码
<div class="col-md-3">
<div>
<ol>
<li *ngFor="let item of videoList" > {{item.title}} </li>
<ol>
<li *ngFor="let subItem of videoList.item.nodes"> {{subItem.title}} </li>
</ol>
</ol>
</div>
</div>
JSON 对象
videoList = [
{
'id':1,
'title':'Lower Extremities',
'nodes':[
{
'id':11,
'title':'Cast Receive',
'nodes':[
{
'id':111,
'title':'Video 1',
'nodes':[
{
'id':1111,
'title':'Working',
'nodes':[]
},
{
'id':1112,
'title':'Stacking',
'nodes':[]
},
]
},
{
'id':112,
'title':'Video 2',
'nodes':[]
},
{
'id':113,
'title':'Video 3',
'nodes':[]
}
]
},
{
'id':12,
'title':'Cast Inspection',
'nodes':[
{
'id':121,
'title':'Video 1',
'nodes':[]
},
{
'id':122,
'title':'Video 2',
'nodes':[]
},
{
'id':123,
'title':'Video 3',
'nodes':[]
}
]
},
{
'id':13,
'title':'Cut & Set',
'nodes':[
{
'id':131,
'title':'Video 1',
'nodes':[]
},
{
'id':132,
'title':'Video 2',
'nodes':[]
},
{
'id':133,
'title':'Video 3',
'nodes':[]
}
]
}
]
}
EDIT我尝试了给定的答案,但收到的只是数字 1、2 和 3 的列表。这就是我所做的。
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<ol>
<li *ngFor="let item of videoList" > {{item.title}} </li>
<ol>
<li *ngFor="let subItem of item['nodes']" > {{subItem.title}} </li>
</ol>
</ol>
`
})
export class AppComponent {
videoList = [
{
'id':1,
'title':'Lower Extremities',
'nodes': [
{
'id':11,
'title':'Second node',
'nodes': "[]"
},
{
'id':12,
'title':'Second node',
'nodes': "[]"
}
]
},
{
'id':2,
'title':'Second node',
'nodes': []
},
{
'id':3,
'title':'third node',
'nodes': []
}
];
}