Search code examples
angularionic-frameworkionic2

Display object data in angular template using dynamic object data


I want to display an object values to template in angular. but my object is dynamic so i do not know its keys. i also tried pipe keyvalues but that is not working for me. i tried one possible solution but not able to complete it.i am getting keys values as an array and object also but not able to parse in ng template here whats i have tried-

data=[
{'a':12,'b':34,'d':32,'w':3}
{'a':2,'b':4,'d':3,'w':23}
{'a':24,'b':24,'d':13,'w':63}
]
key_name=['a','b','d','w']

in html file i am trying to use *ngFor

<ion-row class="data-table data-table-row" *ngFor="let data of tableData">
<ion-col> {{data}}</ion-col>
</ion-row>

*****i am using ionic**** but data is giving [object][object] data is displaying when i am writing key name with it

{{data.a}}

Thanks


Solution

  • You might have to use two *ngFor loops. Try the following

    tableData = [
      {'a':12,'b':34,'d':32,'w':3},
      {'a':2,'b':4,'d':3,'w':23},
      {'a':24,'b':24,'d':13,'w':63}
    ]
    
    <ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
      <ng-container *ngFor="let item of data | keyvalue">    <!-- iterate the object in element of the array -->
        {{ item.key }} : {{ item.value }}
      </ng-container>
    </ng-container>
    

    Or if you do not want to iterate every property of the object, you could use json pipe

    <ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
      {{ data | json }}
    </ng-container>
    

    Or if you still wish to use the key_name array to access the properties of the object, you could try the following

    <ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
      <ng-container *ngFor="let key of key_name">    <!-- iterate the `key_name` array -->
        {{ key }} : {{ data[key] }}
      </ng-container>
    </ng-container>