【问题标题】:How to present Object object in a table using Angular Material如何使用 Angular Material 在表格中呈现对象对象
【发布时间】:2020-10-23 23:40:39
【问题描述】:

我想展示数据 - 这是 Angular Mat Table 中的一个对象 下面的例子:

{
   "first": 15.0,
   "second": [{"id":1,"data_1":"foo","dat_2":"bar"}],
   "third": "2018-09-15T05:30",
   "fourth": ["ONE", "TWO"],
   "fifth": {"data_3":145,"id":2,"data_4":1600}
}

其实我想把它显示在一个表格中,在第一列会有“第一”、“第二”等键,在第二列会有一个值(这可能是一个字符串、数字数组或对象数组。

这里展示了我实际拥有的内容: my current progress - 在 table-basic-example.ts 中有两个元素:正确显示的 ELEMENT_DATA_NEW,但是我想显示 NEW_DATA

注意:我使用角垫对话框打开对话框,该表格将在其中显示。

【问题讨论】:

  • 您可以将 NEW_DATA 转换为数据结构 dataSource 接受

标签: angular typescript angular-material angular-material-table


【解决方案1】:

您需要将 NEW_DATA 转换为 dataSouce:

dataSource = Object.entries(NEW_DATA).map(o => {
    return { name: o[0], value: JSON.stringify(o[1]) };
});

https://stackblitz.com/edit/angular-table-content-of-object-onx5sm

【讨论】:

  • 非常感谢,但是我确实改变了显示数据的方式,因为它对于显示具有大量记录的数据库非常有用,而不是一条记录有多个值连接到一个记录。
【解决方案2】:

您需要将 NEW_DATA 转换为数组。干脆做

dataSource = Object.entries(NEW_DATA); 

并且还改变表格模板。而不是名称/值使用索引。

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
 
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element[0]}} </td>
  </ng-container>
  
  <ng-container matColumnDef="value">
    <th mat-header-cell *matHeaderCellDef> Value </th>
    <td mat-cell *matCellDef="let element"> {{element[1]}} </td>
  </ng-container>

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

https://stackblitz.com/edit/angular-table-content-of-object-5d19au

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多