【问题标题】:Angular dynamic table using ngFor使用 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 页面中不应该硬编码。

【问题讨论】:

    标签: html angular ngfor


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 2019-10-29
      • 1970-01-01
      • 2020-11-23
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2018-04-06
      相关资源
      最近更新 更多