Angular dynamic table using ngFor

前端 未结 2 1171
孤街浪徒
孤街浪徒 2021-01-05 08:23

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

2条回答
  •  长情又很酷
    2021-01-05 08:57

    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:

    {{head}}
    {{item[list]}}

    Update: Here is the demo.

提交回复
热议问题