iteration a json object on Ngfor in angular 2

Anna picture Anna · May 25, 2016 · Viewed 27.1k times · Source

I'm having trouble iteration a json object in the Ngfor, there is my template :

template:

<h1>Hey</h1>
  <div>{{ people| json}}</div>
  <h1>***************************</h1>
  <ul>
    <li *ngFor="#person of people">
        {{
          person.label
        }}
    </li>
 </ul>

people is the json object that I'm trying to iterate, I'm having rhe result of (people | json) and not getting the list, here is a screenshot:

and to finish, here is a part of json file :

{
"actionList": {
"count": 35,
"list": [
    {
    "Action": {
        "label": "A1",
        "HTTPMethod": "POST",
        "actionType": "indexation",
        "status": "active",
        "description": "Ajout d'une transcription dans le lac de données",
        "resourcePattern": "transcriptions/",
        "parameters": [
            {
                "Parameter": {
                    "label": "",
                    "description": "Flux JSON à indexer",
                    "identifier": "2",
                    "parameterType": "body",
                    "dataType": "json",
                    "requestType": "Action",
                    "processParameter": {
                        "label": "",
                        "description": "Flux JSON à indexer",
                        "identifier": "4",
                        "parameterType": "body",
                        "dataType": "json",
                        "requestType": "Process"
                    }
                }
            },

please feel free to help me

Answer

Thierry Templier picture Thierry Templier · May 25, 2016

Your people object isn't an array so you can iterate over it out of the box.

There is two options:

  • You want to iterate over a sub property. For example:

    <ul>
      <li *ngFor="#person of people?.actionList?.list">
        {{
          person.label
        }}
      </li>
    </ul>
    
  • You want to iterate over the keys of your object. In this case, you need to implement a custom pipe:

    @Pipe({name: 'keys'})
    export class KeysPipe implements PipeTransform {
      transform(value, args:string[]) : any {
        if (!value) {
          return value;
        } 
    
        let keys = [];
        for (let key in value) {
          keys.push({key: key, value: value[key]});
        } 
        return keys;
      } 
    } 
    

    and use it this way:

    <ul>
      <li *ngFor="#person of people | keys">
        {{
          person.value.xx
        }}
      </li>
    </ul>
    

    See this answer for more details: