首页 > 解决方案 > mat-table creating columns dynamically vs static change table look

问题描述

Sorry if this question is trivial, I'm very new to Angular and Web UI Kingdom

I'm currently looking at this sample project: https://github.com/marinantonio/angular-mat-table-crud

I was replacing the way the columns were created (from static to dynamic) and the table layout changed into something that is hard to read. I am having trouble understanding how/why this is happening. What makes the difference in how I created my columns? But, most importantly, how do i fix it?

Here is what I have:

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']);

I didn't touch the components.css

enter image description here

标签: angularangular-materialmat-table

解决方案


我找到了解决方案!!!

使用 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>

推荐阅读