我有一个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':[]
}
]
}
]
}
修改 我尝试了给出的答案,我收到的只是一个数字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': []
}
];
}
答案 0 :(得分:5)
第二个for
循环应为
<li *ngFor="let subItem of item['nodes']"> {{subItem.title}} </li>
答案 1 :(得分:2)
我遇到的问题是我没有在之前的<li>
标记中正确嵌套连续的<li>
元素。这是它应该如何。
<div>
<ol>
<li *ngFor="let item of videoList" >
<div>{{item.title}}</div>
<ol>
<li *ngFor="let subItem of item.nodes">
<div>{{subItem.title}}</div>
</li>
</ol>
</li>
</ol>
</div>