Search code examples
angularangular-materialmat-table

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


Solution

  • I found the solution!!!

    use cdkColumnDef and cdkHeaderCellDef instead of matColumnDef and mat-header-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>