How can i access nested json data in angular2
this is my app.component.ts
@Component({
selector: 'my-app',
template: `<h1>{{title}}</h1>
{{test | json}}
<div ngFor='let test of tests' style='border: solid 1px'>
<div>
<P>
writer: {{test.A.B.C.D.writerid}} <br>
content:{{test}}<br>
write_date:{{test}}</P>
</div>
</div>
`,
})
public test: any[] = [
{
'A': {
'B': [{
'C': {
'D': [{
'content': 'content_test1',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test1'
}, {
'content': 'content_test2',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test1'
}, {
'content': 'content_test3',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test2'
}, {
'content': 'content_test4',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test2'
}]
}
}]
}
}
];
test.ABCDwriterid does not work error: Cannot read property "B" undefined I don't understand why the error is not A but B how can I access the contents of D or writedt or writid
source to share
First of all, I am assuming that you have typos in your template (for example ngFor
) and that the array is actually called tests
, but ignore it.
I think you want to iterate through the array D
. Without making any changes to your data structure, you can do this with nested *ngFor
: s.
So first, your array must be named tests
, not test
. And how to access the innermost array, we first go to the array tests
, then we go through the array, B
and finally the innermost array D
. So your template will look like this:
<div *ngFor="let test of tests">
<div *ngFor="let x of test.A.B">
<div *ngFor="let y of x.C.D; let i = index"> <h4>Content {{i+1}}</h4>
{{y.content}}
{{y.writedt | date}}
{{y.writerid}}
</div>
</div>
</div>
DEMO
source to share