How to populate an html table with json array values in angular?

Viewed 575

I have an array as below;

var publicArray={
"settings": [{
"id": "1",
"deleted": "0",
"data": [{
"title": " Business Unit",
"value": "B1"
},
{
"title": "Comp ",
"value": "C1"
},
{
"title": " Pa Id",
"value": "P1"
}, {
"title": " NPI",
"value": "4535"
}
]
}, {
"id": "2",
"deleted": "0",
"data": [{
"title": " Business Unit",
"value": "B2"
},
{
"title": "Comp ",
"value": "C2"
},
{
"title": " Pa Id",
"value": "P2"
}, {
"title": " NPI",
"value": "34242"
}
]
}]
};

the array comes actually from database so it may extend to more.so that more rows would come as the array grows. and I need to populate a html table using this array as follow imagethis is how the table looks like.i am new to this please help me to do this

3 Answers
<table>
  <thead>
    <th>ID</th>
    <th>Business Unit</th>
    <th>Comp</th>
    <th>Pa Id</th>
    <th>NPI</th>
  </thead>
  <tbody>
    <tr *ngFor="let item of data.settings; let i=index">
      <td>{{item.id}}</td>
      <td *ngFor="let item2 of item.data">{{item2.value}}</td>
    </tr>
  </tbody>
</table>

stackblitz example

preview

Having component's property called publicArray you can you can achive that by writing the following template:

<table *ngIf="publicArray?.settings?.length && publicArray.settings[0].data?.length">
  <tr>
    <th>ID</th>
    <th *ngFor="let header of publicArray.settings[0].data">{{ header.title }}</th>
  </tr>
  <tr *ngFor="let row of publicArray.settings">
    <td>{{ row.id }}</td>
    <td *ngFor="let col of row.data">
      {{ col.value }}
    </td>
  </tr>
</table>

Ng-run Example

There are many libraries that you can use to create a table like "PrimeNG", "Angular material" ....
I'll give you this example "of ngx smart table":
https://www.npmjs.com/package/ngx-smart-table.
you can follow the documantations:

  • By setting the seetings{} object you'll define your table header
  • then define another object from your brought data publicArray so that it can match the same names as it in the settings{}
Related