如何在Angular材质表的数据源中呈现所有可用列?

时间:2019-07-18 09:34:16

标签: angular typescript angular-material

我正在尝试从官方文档here生成Angular材质mat-table

我的表大约有10列。我想知道是否有可能在数据源上显示所有可用的列,而不用在HTML中键入十个不同的属性?

1 个答案:

答案 0 :(得分:0)

您可以使用*ngFor并显示列,标题;对于实际值,您可以在TS文件中编写代码;

相关的 HTML

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

    <ng-container *ngFor='let disCol of displayedColumns; let i = index'>
        <ng-container matColumnDef="{{disCol}}">
            <th mat-header-cell *matHeaderCellDef> {{disCol}} </th>
            <td mat-cell *matCellDef="let element"> {{returnVal(element, disCol)}} </td>
        </ng-container>
    </ng-container>

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

相关的 TS

import {Component} from '@angular/core';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
  returnVal(element, dispCol){
    switch(dispCol){
      case 'position': return element.position;
      case 'name': return element.name;
      case 'weight': return element.weight;
      case 'symbol': return element.symbol;
    }
  }
}

完成working stackblitz here