Angular 动态 table 使用 ngFor

Angular dynamic table using ngFor

我想知道是否可以从 JSON 数据创建动态 HTML table。列数和 headers 应根据 JSON 中的键而变化。例如这个 JSON 应该创建这个 table:

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

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

 ...

而这个 JSON 应该创建这个 table:

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

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

...

不过这必须是 100% 动态的,因为我想显示数百种不同的 JSON objects,因此 HTML 页面中不应进行任何硬编码。

如果你想把你的对象的键作为你的table的头部,你应该创建一个

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;
  }
}

更新: 或者简单地使用 Object.keys() return 键。 (demo)

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

现在进入您的 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>

更新: 这是demo.

这可以帮助:

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>