3

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

4

2 回答 2

3

我找到了解决方案!!!

使用 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>
于 2018-11-16T18:39:34.903 回答
3

此解决方案适用于 Angular 6+

<ng-container *ngFor="let i = index; let column of columnsToDisplay" 
    matColumnDef="{{column}}">
    <th mat-header-cell *matHeaderCellDef> {{column | titlecase}} </th>
    <td mat-cell *matCellDef="let element">
       <span *ngIf="column !== 'action'">{{element[column]}}</span>
        <span *ngIf="column == 'action'">
          <button mat-icon-button (click)="deleteRowData(element)" 
            color="primary">
            <mat-icon>delete</mat-icon>
          </button>
        </span>
    </td> 
</ng-container>
于 2020-01-09T13:38:46.517 回答