使用ngFor的角动态表 [英] Angular dynamic table using ngFor
问题描述
我想知道是否可以根据JSON数据创建动态HTML表.列和标题的数量应根据JSON中的键进行更改.例如,此JSON应该创建此表:
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"
}
...
并且此JSON应该创建此表:
And this JSON should create this table:
{
id: "1", type: "bus", make: "VW", color: "white"
}
,
{
id: "2", type: "taxi", make: "BMW", color: "blue"
}
...
这必须是100%动态的,因为我想显示数百个不同的JSON对象,因此在HTML页面中不应硬编码任何内容.
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.
推荐答案
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;
}
}
更新:或者只需使用 Object.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);
}
}
现在进入您的html模板:
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>
更新:这是演示.
这篇关于使用ngFor的角动态表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!