首页 > 解决方案 > 在 Angular 中使用列数据填充数据表中的行

问题描述

我对 Angular 很陌生,我正在设置一个数据表来从一个类中获取信息,并在单独的行而不是列中显示我的数据源中一行中的多个项目的信息。

因为我可以有任意多的行,所以我不能将所有数据硬编码到表中。

数据来自电子表格,其中每一行代表一个更大的实体,电子表格的每一列要么是我表中的一行,要么是我表中列的关联属性。

我看过https://material.angular.io/components/table/examples但它没有帮助我。

列名称:ID、Attr1_desc、Attr1_value、Attr2_desc、Attr2_value。我希望每个属性位于单独的行上,每个 attr_desc 和 att_value 都是它自己的列。该表包含来自我的电子表格单行的数据。

由于列名不是我想要的单元格值,所以我也不确定如何应用逻辑来格式化名称(例如,应将 Attr1 称为 Character 而不是 Attr1)。

数据源:

export interface MyData {
  ID: number,
  attr1Desc: number,
  attr1Value: string,
  attr2Desc: number,
  attr2Value: string
}

HTML:

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="Attribute_No">
    <th mat-header-cell *matHeaderCellDef>Attribute No</th>
    <td mat-cell *matCellDef="let attr">
      <div *ngIf="attr == attr1">Character</div>
      <div *ngIf="attr == attr2">World</div>
    </td>
  </ng-container>
  <ng-container matColumnDef="Attr_desc">
    <th mat-header-cell *matHeaderCellDef>Attribute Description</th>
    <td mat-cell *matCellDef="let attr_desc">{{attr_desc}}</td>
  </ng-container>
  <ng-container matColumnDef="Attr_value">
    <th mat-header-cell *matHeaderCellDef>Attribute Value</th>
    <td mat-cell *matCellDef="let attr_value">{{attr_value}}</td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</mat-table>

TS:

import sampleData from 'data.json';

export class RowDataComponent {
  displayedColumns: string[] = ['Attribute_No', 'Attr_desc', 'Attr_value']
  data: string[] = ['Attr_1', 'Attr_2'];
  dataSource = new MatTableDataSource(sampleData);
}

应该有三列:属性、描述、值,每一行应该是不同的属性。如此处所示

标签: angularangular-material

解决方案


<ng-container matColumnDef="Attr_desc">
    <th mat-header-cell *matHeaderCellDef>Attribute Description</th>
    <td mat-cell *matCellDef="let attr_desc">{{attr_desc}}</td>
</ng-container>

matCellDef -> 这里的变量 'attr_desc' 包含元素,你可以放置let element和使用{{element.attr_desc}}


推荐阅读