按列值对表格进行排序

时间:2019-03-17 21:44:33

标签: angular columnsorting mat-table

我有一张带客户信息的桌子。我想按列值对行进行排序。没有错误,但排序不起作用。

表标记具有matSort

<mat-table [dataSource]="dataSource" matSort>

每个列定义都有mat-sort-header

<ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
  <mat-cell *matCellDef="let customer"> {{customer.name}} </mat-cell>
</ng-container>

在组件类中,我有

...
@ViewChild(MatSort) sort: MatSort;
...
ngOnInit() {
    this.dataSource = new MatTableDataSource(this.data as any);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
}

所以一切都非常类似于the documentation中的状态

  

如果您将MatTableDataSource用于表的数据源,   向数据源提供MatSort指令,它将   自动侦听排序更改并更改数据顺序   由表格呈现。

但样式或排序功能均未应用于表。

This question无关紧要,因为即使我的数据在类中进行了硬编码,问题仍然存在。

我看不到我想念的东西。 问题的根源在于逃避我。您可以查看我的完整代码并运行example on Stackblitz

1 个答案:

答案 0 :(得分:2)

Looking at your Stackblitz, the MatSort module was not part of your exports in the mat.module.ts file. Corrected StackBlitz is here.

So for others finding the same issue, the code is using a single module to select all the Material modules that should be available to the app. Any other modules in the app then only need to reference this single module, rather than each Material modules themselves.

However, to make this work, this single module (mat.module.ts) needs to export anything that it wants to expose to others when it is imported. In this case, it's anything it imported from Material.

So the fix was:

@NgModule({
    imports: [
        CommonModule,
        // ... other modules
        MatSortModule,
        // ... other modules
    ],
    exports: [
       // ... other modules
        MatSortModule, // <---------- This export was missing
        // ... other modules
    ]
})
export class MatModule {
}