Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 645
BlueCat Avatar asked Jan 23 '18 12:01

BlueCat


2 Answers

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

like image 140
Vivek Doshi Avatar answered Nov 01 '22 21:11

Vivek Doshi


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"}
    ]
  }
  ];
}
like image 6
Pac0 Avatar answered Nov 01 '22 21:11

Pac0