0

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

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

3
  • 1
    what does it display? Commented Oct 18, 2022 at 8:56
  • @nosTa, I've added a pic Commented Oct 18, 2022 at 9:00
  • do you have a css file configured? Commented Oct 18, 2022 at 9:17

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.