使用ngFor的角度动态表

Fra*_*ank 3 html ngfor angular

我想知道是否可以从JSON数据创建动态HTML表.列和标头的数量应根据JSON中的键进行更改.例如,这个JSON应该创建这个表:

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

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

 ...
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这个JSON应该创建这个表:

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

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

...
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这必须是100%动态,因为我想显示数百个不同的JSON对象,因此HTML页面中不应对任何内容进行硬编码.

Rad*_*ina 13

如果要将对象的键作为表头,则应创建自定义管道.

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在进入你的html模板:

<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>
Run Code Online (Sandbox Code Playgroud)

更新:这是演示.