Angular dynamic table using ngFor
Asked Answered
S

2

12

I would like to know if it is possible to create a dynamic HTML table from JSON data. The amount of columns and headers should change according to the keys in the JSON. For example this JSON should create this table:

{
     color: "green", code: "#JSH810"
 }

 ,
 {
     color: "red", code: "#HF59LD"
 }

 ...

enter image description here

And this JSON should create this table:

{
    id: "1", type: "bus", make: "VW", color: "white"
}

,
{
    id: "2", type: "taxi", make: "BMW", color: "blue"
}

...

enter image description here

This has to be 100% dynamic though, because I want to display hundreds of different JSON objects, so nothing should be hard coded in the HTML page.

Sartain answered 26/3, 2018 at 12:54 Comment(0)
G
32

If you want to get the key of your object as the head of your table, you should create a custom pipe.

import { PipeTransform, Pipe } from '@angular/core';

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

Update: Or simply return keys using Object.keys(). (demo)

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    return Object.keys(value);
  }
}

Now into your html template:

<table>
  <thead>
    <tr>           
      <th *ngFor="let head of items[0] | keys">{{head}}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of items">           
      <td *ngFor="let list of item | keys">{{item[list]}}</td>
    </tr>
  </tbody>
</table>

Update: Here is the demo.

Gaffney answered 26/3, 2018 at 13:12 Comment(2)
Hey man. Thank you for your answer! It works well with the headers, but the list of values are not displaying, I don't understand why not though. Mind helping please? Here is a project to check with stackblitz.com/edit/…Sartain
Update my answerGaffney
G
3

This can help:

export class AppComponent {
 //Array of any value
  jsonData:any = [
    {id: "1", type: "bus", make: "VW", color: "white"},
    {id: "2", type: "taxi", make: "BMW", color: "blue"}
  ];
  _object = Object;
}
<div>
  <table border="1">
    <thead>
      <tr>
        <th *ngFor="let header of _object.keys(jsonData[0]); let i = index">{{header}}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let row of jsonData; let i = index">
        <th *ngFor="let objKey of _object.keys(row); let j = index">{{ row[objKey] }} </th>
      </tr>
    </tbody>
  </table>
</div>
Glory answered 26/3, 2018 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.