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

31,444

Solution 1

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"}
    ]
  }
  ];
}

Solution 2

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

Share:
31,444
BlueCat
Author by

BlueCat

Updated on July 09, 2022

Comments

  • BlueCat
    BlueCat almost 2 years

    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