I I have a JSON object that has several levels of nest objects as well as nested arrays of objects. I would like to know how to use Angular2 and *ngFor to iterate through the object and end up with the listed printed out. The first *ngFor works but the next *ngFor give me and error saying Cannot read property nodes of undefined
Current HTML code
<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 object
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 I attempted the given answer and all I recieved was a list of numbers 1, 2, and 3. Here is what I did.
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': []
}
];
}
The problem I was having was I was not nesting the successive <li>
elements properly in the previous <li>
tags. Here is how it should have been.
<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>
The second for
loop should be
<li *ngFor="let subItem of item['nodes']"> {{subItem.title}} </li>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With