Search code examples
htmljsonangularangular2-template

How to get the length of the json object in Angular 2 template


I have a array of json like this.

[
  {
    "variations": {
      "title": {
        "newValue": "test new value1",
        "oldValue": "test old value1"
      }
    }
  },
  {
    "variations": {
      "data": {
        "newValue": "new data",
        "oldValue": "httpold data"
      },
      "length": {
        "newValue": "48",
        "oldValue": "9.00"
      }
    }
  }
]

from this i want to get the length of the variations in Html and also render and values to view.

<table class="table table-bordered table-hover">
                        <thead class="table-title">
                            <tr>
                                <th class="text-center">Field count</th>
                                <th class="text-center">Field Name</th>
                                <th class="text-center">Old Value</th>
                                <th class="text-center">New Value</th>
                            </tr>
                        </thead>
                        <tbody *ngFor="let data of datas">
                            <tr>
                                <td class="text-left" rowspan="2">{{data.variations.length}}</td>
                                <td class="text-left" rowspan="2"></td>
                                <td class="text-left" rowspan="2"></td>
                            </tr>
                            <tr>
                            </tr>
                        </tbody>
                    </table>

In the above code how can i get the length of variation data. also need to render and show all the new field and old field value to the view. can any one please help me


Solution

  • Component side :

    objectKeys = Object.keys;
    

    Template Side :

    <tbody *ngFor="let data of datas">
        <tr>
            <td class="text-left" rowspan="2">{{objectKeys(data.variations).length}}</td>
            ...
        </tr>
        ...
    </tbody>
    

    WORKING DEMO