使用 ngFor 的角度动态表

Posted

技术标签:

【中文标题】使用 ngFor 的角度动态表【英文标题】:Angular dynamic table using ngFor 【发布时间】:2018-09-04 15:05:16 【问题描述】:

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


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

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

 ...

这个 JSON 应该创建这个表:


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


,

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


...

这必须是 100% 动态的,因为我想显示数百个不同的 JSON 对象,所以 HTML 页面中不应该硬编码。

【问题讨论】:

【参考方案1】:

如果你想获取对象的键作为表头,你应该创建一个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()返回密钥。 (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。

【讨论】:

嘿伙计。谢谢您的回答!它适用于标题,但没有显示值列表,我不明白为什么不显示。介意帮忙吗?这是一个与stackblitz.com/edit/…检查的项目 更新我的答案【参考方案2】:

这会有所帮助:

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>

【讨论】:

以上是关于使用 ngFor 的角度动态表的主要内容,如果未能解决你的问题,请参考以下文章

使用 ngFor 的角度动态表

ng-repeat:动态颜色表背景

如何根据数据表角度中的 JSON 动态填充表值?

具有动态标题和角度动态值的垂直表

是否可以使用额外的指令创建有角度的材料垫表组件但仍保持列动态?

如何将角度材料表与后端数据动态绑定?