Stack Underflow
Stack Underflow

Reputation: 2453

Sorting mat-table by column value

I have a mat-table with customer info. I would like to sort the rows by column value. There is no error but the sorting is not working.

The table tag has matSort:

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

Each column definition has 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>

In the component class I have

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

So everything is pretty much like in the documentation which states

If you are using the MatTableDataSource for your table's data source, provide the MatSort directive to the data source and it will automatically listen for sorting changes and change the order of data rendered by the table.

but neither the styling nor the functionality for sorting is being applied to the table.

This question is not relevant because the problem is present even with my data hardcoded in the class.

I don't see what I am missing. The root of the problem is evading me. You can see my full code and run the example on Stackblitz

Upvotes: 1

Views: 3055

Answers (1)

Matt Tester
Matt Tester

Reputation: 4814

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 {
}

Upvotes: 2

Related Questions