首页 > 解决方案 > 动态使用 Angular6 Mat-Table

问题描述

我正在开发一个 Angular 应用程序,它需要显示从 API 检索到的数据。由于我不确切知道我将检索哪些数据,而且这是我需要用于不同表的模型,我需要让它既动态生成列,又填充每个单元格。

我检索并需要在表中打印的 JSON 类似于:

[
    {
        "attributes": [],
        "brandReference": "f805a08df4c236ddb431e14a38419690",
        "computedPOS": "BEXFY_HEADQUARTERS",
        "deviceType": 1,
        "friendlyName": "BEXFY_TRANSPARENT_LED",
        "id": "953e9414d7a51e8-e0-681def0b02b5",
        "isMonitored": true,
        "location": "entrance",
        "posReference": "78fcef0f12993d52b2d2906dc4ce48d8",
        "timetable": [],
        "timezone": "Europe/Madrid"
    },
    {
        "attributes": [],
        "brandReference": "185fd549-4410-462b-a610-fe6b61c91cf6",
        "comments": "",
        "computedPOS": "BEXFY_HEADQUARTERS",
        "deviceType": 1,
        "friendlyName": "BEXFY_AUDIO_OFICINA",
        "id": "79eaa7f5f6603809-e0-681def0b0290",
        "location": "",
        "posReference": "78fcef0f12993d52b2d2906dc4ce48d8",
        "timetable": [],
        "timezone": "Europe/Madrid"
    },
    {
        "attributes": [],
        "brandReference": "185fd549-4410-462b-a610-fe6b61c91cf6",
        "comments": "",
        "computedPOS": "BEXFY_HEADQUARTERS",
        "deviceType": 1,
        "friendlyName": ".BEXFY_AUDIO_ADRI",
        "id": "97bf675e3e237bcd-e0-681def0b029f",
        "location": "",
        "posReference": "78fcef0f12993d52b2d2906dc4ce48d8",
        "timetable": [],
        "timezone": "Europe/Madrid"
    }
]

请注意,对象属性键可能会更改,因此我无法对 element.friendlyName 之类的内容进行硬编码。我通过如下所示的数组接收我应该使用的键名。

["friendlyName", "computedPOS", "location"]

所以为了让它发挥作用,我做了这样的东西。

<table mat-table [dataSource]="dataSource.data" class="mat-elevation-z8" style="width:90%;margin:0 auto;">

  <ng-container *ngFor="let column of modelCols; let colIndex = index" matColumnDef={{nameCols[colIndex]}}>
    <th mat-header-cell *matHeaderCellDef> {{nameCols[colIndex]}}</th>
    {{log(modelCols)}}
    <div *ngFor="let column of modelCols;">
      <td mat-cell *matCellDef="let element">
        {{log(element[column])}}
        {{element[column]}}
      </td>
    </div>

  </ng-container>

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

这样做的问题是,它会导致在行的每一列上重复第一个值(“friendlyName”)。像这样的东西。

在此处输入图像描述

虽然预期的工作方式是这样的:

在此处输入图像描述

标签: javascriptangularangular-material

解决方案


您需要循环nameCols显示您的动态列。无论您的 API 要求您显示什么列,您都需要迭代以显示您的列。由于您element[column]用于在行中显示项目。它只会显示需要的项目。

<ng-container *ngFor="let column of nameCols; let colIndex = index" [matColumnDef]="column">
    <th mat-header-cell *matHeaderCellDef>{{column}}</th>
    <td mat-cell *matCellDef="let element">{{element[column]}}</td>
</ng-container>

这是StackBlitz上的一个工作示例,其中包含您的数据。这样即使一组不同的列来自 API 来显示,您需要做的只是更新nameCols以显示正确的列。模板将处理其余部分并将相关数据显示到显示的列中。


推荐阅读