Home > OS >  Iterate nested objects using ngFor
Iterate nested objects using ngFor

Time:12-21

I have JSON object:

content = 
[
{
   "id":1,
   "name":"test",
   "parent":{
      "name":"test2",
      "subParent":{
         "name":"test3",
         "subParent":{
            "name":"test4",
            "subParent":{
               "name":"test5",
               "subParent":null
            }
         }
      }
   }
}
]

How to iterate through each nested object and display the data in Angular?

I tried to do it with ngFor but it doesn't work

CodePudding user response:

There's a number of options, but one that might be helpful here is recursive templates. There's some good examples by Nethanel Basal

This is especially useful if the depth of the nesting is dynamic

Example from above article

@Component({
  selector: 'comments',
  template: `
     <div *ngFor="let comment of comments">
      <ul>
       <li>
         {{comment.text}}
         <comments [comments]="comment.comments" *ngIf="comment.comments"></comments>
       </li>
      </ul>
    </div>
  `,
})
export class CommentComponent {
  @Input() comments;
}

CodePudding user response:

<ul>
  <li *ngFor="let data of content">
    {{data.id}}
    <ul>
      <li *ngFor="let p of data.parent">
        {{p.name}}
      </li>
    </ul>
  </li>
</ul>

You can try something like that, but recursive templates is for me, the right way to do that.

Regards,

  • Related