Html 使用 ngFor 的角度动态表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49491982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular dynamic table using ngFor
提问by Frank
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:
我想知道是否可以从 JSON 数据创建动态 HTML 表。列和标题的数量应该根据 JSON 中的键而改变。例如这个 JSON 应该创建这个表:
{
color: "green", code: "#JSH810"
}
,
{
color: "red", code: "#HF59LD"
}
...
And this JSON should create this table:
这个 JSON 应该创建这个表:
{
id: "1", type: "bus", make: "VW", color: "white"
}
,
{
id: "2", type: "taxi", make: "BMW", color: "blue"
}
...
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.
不过,这必须是 100% 动态的,因为我想显示数百个不同的 JSON 对象,因此不应在 HTML 页面中硬编码任何内容。
回答by Radonirina Maminiaina
If you want to get the key of your object as the head of your table, you should create a custom pipe.
如果您想将对象的键作为表的头部,您应该创建一个自定义 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)
更新:或者简单地使用Object.keys()返回键。(演示)
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
return Object.keys(value);
}
}
Now into your html template:
现在进入你的 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>
Update: Here is the demo.
更新:这是演示。
回答by Sachink
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>