mat-table动态创建列与静态更改表外观

时间:2018-11-16 16:33:01

标签: angular angular-material mat-table

很抱歉,如果这个问题很琐碎,我对Angular和Web UI王国还是陌生的

我目前正在看这个示例项目:https://github.com/marinantonio/angular-mat-table-crud

我正在替换创建列的方式(从静态到动态),并且表布局变为难以读取的形式。我无法理解这种情况。什么使我创建列的方式有所不同?但是,最重要的是,我该如何解决?

这是我所拥有的:

componnent.html:

<ng-container *ngFor="let column of columns" matColumnDef="{{column.name}}">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>{{column.label}}</th>
  <td mat-cell *matCellDef="let row"> {{row[column.name]}} </td>
</ng-container>

component.ts

columns: Array<any> = [
    { name: 'id',         label: 'ID',         cell: (element: any) => `${element.id}` },
    { name: 'title',      label: 'Title',      cell: (element: any) => `${element.title}` },
    { name: 'state',      label: 'State',      cell: (element: any) => `${element.state}` },
    { name: 'url',        label: 'Url',        cell: (element: any) => `${element.url}`},
    { name: 'created_at', label: 'Created at', cell: (element: any) => `${element.created_at}`},
    { name: 'updated_at', label: 'Updated at', cell: (element: any) => `${element.updated_at}`},
]
// displayedColumns = ['id', 'title', 'state', 'url', 'created_at', 'updated_at', 'actions'];
displayedColumns = this.columns.map(x => x.name).concat(['actions']);

我没碰过components.css

enter image description here

2 个答案:

答案 0 :(得分:1)

我找到了解决方案!

使用cdkColumnDef和cdkHeaderCellDef代替matColumnDef和mat-h​​eader-cell

<ng-container *ngFor="let column of columns; let colIndex = index" [cdkColumnDef]="column.name">
    <mat-header-cell *cdkHeaderCellDef>{{ column.label }}</mat-header-cell>
    <mat-cell *cdkCellDef="let row">{{ row[column.name] }}</mat-cell>
  </ng-container>

答案 1 :(得分:1)

此解决方案适用于Angular 6 +

{
 currentGame: {
  players: {
   playerId: {...playerGameData},
   //,
  },
  noOfPlayer: // this is what i wanted to create based on above players node children_count.
 }
}