带有自定义列的自定义 Angular 6 material table 组件

Custom Angular 6 material table component with custom columns

我正在尝试使用自定义 material table 组件简化创建 table 的过程,其中只需很少的代码,我就可以为每个不同的组件创建一个非常自定义的 table已附加分页和排序的数据源。我只需要通过 displayedColumnsdata。基于示例 here I built this(https://stackblitz.com/edit/angular-kp2ryv),但由于某些原因,我在尝试使用自定义列组件时在 StackBlitz 中遇到错误。

ERROR TypeError: Cannot set property 'name' of undefined

这告诉我 @ViewChild(MatColumnDef) columnDef: MatColumnDef; 出于某种原因没有阅读模板中的 matColumnDef

示例 table 使用自定义组件创建:

<dyn-table [data]="users" [displayedColumns]="displayedColumns">
    <dyn-col name="user_id"></dyn-col>
    <dyn-col name="user_name"></dyn-col>
</dyn-table>

这将取代所有这些:

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

    <ng-container matColumnDef="user_id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> User id </th>
        <td mat-cell *matCellDef="let data">{{ data.user_id }}</td>
    </ng-container>

    <ng-container matColumnDef="user_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> User name </th>
        <td mat-cell *matCellDef="let data">{{ data.user_name }}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [pageSize]="10"></mat-paginator>

我花了 2 天时间在谷歌上搜索、反复试验和出错,但我不明白为什么它不读。

同一 StackBlitz 的工作分支,但没有自定义列组件https://stackblitz.com/edit/angular-jw9whh

原因是您使用 @angular/material 模块中的 material 指令定义了 NgModule,但现在正试图访问 @angular/material/table 模块中的指令。

只是一个小测试:

import {MatColumnDef} from '@angular/material/table';
import {MatColumnDef as RooColumnDef } from '@angular/material';

console.log(MatColumnDef, RooColumnDef, MatColumnDef === RooColumnDef);
                                                      ||
                                                     false

所以你可以猜到 MatTableModuleMatColumnDef 应该从同一个模块导入。

Forked Stackblitz