aid85
aid85

Reputation: 9

Angular: Iterate over Array of objects

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:

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

EDIT: thanks everyone, I decided to change the array structure to more linear. It works fine now

Upvotes: 0

Views: 101

Answers (2)

nosTa
nosTa

Reputation: 658

If you want to display it in a list you can use the HTML list elements ul / li. In your approach you get the data but not displayed correctly. When using ul / li elements it should work as expected.

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

working code

Upvotes: 0

Tommi
Tommi

Reputation: 444

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: https://stackblitz.com/edit/angular-ivy-9rjnpr?file=src/app/app.component.html

Upvotes: 1

Related Questions