0

How can I render this array of objects in Angular?

var list = [{
    collaborators: [{
      id: 1,
      name: "test"
    }]
  },
  {
    colleagues: [{
      id: 2,
      name: "colleague2"
    }]
  }
]

I tried in this way

<div *ngFor="let el of list">
  <div *ngFor="let e of el.collaborators">
    {{e.id}}
  </div>
</div>

But it doesn't work

1
  • 1
    yes, this doesn't work because the array name is different: collaborators and colleagues. And in HTML you are accessing only collaborators. Commented Oct 19, 2020 at 3:56

2 Answers 2

1

Lets break down your list

list[0] will give

{collaborators: [{id: 1, name: "test"}]},

and list[1] will give

{colleagues: [{id:2, name: "colleague2"}]}

Lets now loop

   <div *ngFor="let e of list[0].collaborators">
     {{e.id}}
   </div>
  <div *ngFor="let e of list[1].colleagues">
     {{e.id}}
   </div>

We can also combine them like

  <div *ngFor="let e of list">
     <ng-container *ngIf=' e.collaborators'>
        <div *ngFor='let collaborator of e.collaborators'>
            {{ collaborator.id }}
         </div>
     </ng-container>
     <ng-container *ngIf=' e.colleagues'>
        <div *ngFor='let colleague of e.colleagues'>
            {{ collaborator.id }}
         </div>
     </ng-container>
   </div>
Sign up to request clarification or add additional context in comments.

Comments

0

You are missing (let e) :

   <div *ngFor="let e of el.collaborators">
     {{e.id}}
   </div>

2 Comments

No...it was an error of transcription. It doesn't work also with "let" declaration
Is list part of the component scope? constructor() { this.list=[...]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.