BlueCat
BlueCat

Reputation: 763

Loop through array of JSON object with *ngFor (Angular 4)

I want to loop through an array of objects, which is in my json file.

Json

[
  {
    "name": "Mike",
    "colors": [
      {"name": "blue"},
      {"name": "white"}
    ]
  },

  {
    "name": "Phoebe",
    "colors": [
      {"name": "red"},
      {"name": "yellow"}
    ]
  }
]

html

<div *ngFor="let person of persons">
   <p>{{person.name}}</p> <!-- this works fine-->
   <p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
     {{color.name}}
   </p>
</div>

I cant access the colors array of a person. How do I achieve that?

I've already looked at these posts but the solutions of them couldn't help me:

Angular2 ngFor Iterating over JSON

Angular2 - *ngFor / loop through json object with array

Upvotes: 9

Views: 37519

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58613

For Angular 6.1+ , you can use default pipe keyvalue ( Do review also ) :

<ul>
    <li *ngFor="let recipient of map | keyvalue">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

WORKING DEMO


Previously : As you are saying :

Angular2 - *ngFor / loop through json object with array , this couldn't help you

You dont have any need of that, coz your code works fine , please check

WORKING DEMO

Upvotes: 16

Pac0
Pac0

Reputation: 23174

Your code (the part you shown) works fine (see the plunker linked below).

As the only thing not shown in your question is the way you assign your Javascript Object to the variable persons, I urge you to show you more code / search the issue there.

https://plnkr.co/edit/rj4K2sKHTHsVtdt4OWfC?p=preview

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div *ngFor="let person of persons">
        <p>{{person.name}}</p> <!-- this works fine-->
        <p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
           {{color.name}}
        </p>
      </div>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {

  }

  persons = [
  {
    "name": "Mike",
    "colors": [
      {"name": "blue"},
      {"name": "white"}
    ]
  },

  {
    "name": "Phoebe",
    "colors": [
      {"name": "red"},
      {"name": "yellow"}
    ]
  }
  ];
}

Upvotes: 6

Related Questions