Home > Enterprise >  Angular: Iterate over Array of objects
Angular: Iterate over Array of objects

Time:10-18

I have some troubles with iterating over an array of objects. In each object I have a name, but some objects have their own arrays. The structure looks like this:

const arr = [{name:1},{name:2}, {name: '1234', childrenId: 'id', children: [{name:3},{name:4}]}]

And I need display it in this way expected result - list of the names:

  • 1
  • 2
  • 1234
  • 3
  • 4

I've tried this approach

<div *ngFor="let item of arr;">
   {{ item.name }}
  <ng-container *ngIf="item.childrenId">
     <ng-container *ngFor="let child of item.children">  {{ child.name }} </ng-container>
  </ng-container>
</div>

But it displays not in exactly way I need, there is some overlap of children on regular items: Pic

CodePudding user response:

You can utilize the html list-element instead of doing ng-containers. Also as @nosTa mentions in the comments it looks like you have some extra css included that is messing with the layout so its hard to reproduce, but I've created a stackblitz that you can take a look at here: working code

  • Related