【问题标题】:Creating Dynamic Angular Material table from JSON data从 JSON 数据创建动态角度材料表
【发布时间】:2020-12-17 02:26:21
【问题描述】:

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

{
     color: "green", code: "#JSH810"
}
,
{
     color: "red", code: "#HF59LD"
}
        Color          Code

        green         #JSH810
        red           #HF59LD

这个 JSON 应该创建这个表:

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

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

      id     type      make     color

      1      bus       VM        white
      2      taxi      BMW       blue

它应该是一个材料表,我知道如何在 HTML 表中使用 ngFor 实现这一点

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

谁能帮我把它转换成材料表?

【问题讨论】:

标签: angular


【解决方案1】:

这是角度材料表示例的示例基础,您可以查看here

表格需要两个东西显示列列表和数据源,

  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;

对于模板

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container [matColumnDef]="col" *ngFor="let col of  displayedColumns">
    <th mat-header-cell *matHeaderCellDef> {{col | uppercase}} </th>
    <td mat-cell *matCellDef="let element"> {{element[col]}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

我使用 ngFor 来设置死区 还有一个示例,您将从 api 请求中获取数据源,您可以通过从Object.keys method 的响应中获取任何对象的键来获取列键

export class TableBasicExample {
  displayedColumns: string[];
  dataSource :any[];

  ngOnInit(){
    // http request to get the data 
    this.dataSource = ELEMENT_DATA
    this.displayedColumns= Object.keys(ELEMENT_DATA[0])
  }
}

demo ?

【讨论】:

  • 但是对于这个,displayColumns 数组是硬编码的吧?我希望根据我的 JSON 数据动态获取它,这可能吗?
  • 由于这里的dataSource是any[]类型,所以不支持分页和排序。有什么方法可以实现任何类型的存在吗?
  • 谢谢@malarmavi。我成功满足了我的要求。
猜你喜欢
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 2019-12-27
相关资源
最近更新 更多