Mat-table Sorting Demo not Working

For anyone else who may have this problem: The problem was I didn't read the API reference properly on the angular materials website, the part that said I had to import MatSortModule. After I changed my imports list in app.module.ts to

imports: [
    BrowserModule,
    MatTableModule,
    MatSortModule
  ],

it worked fine


I had a problem that the sorting function was working but it wasn't sorting properly. I realized that matColumnDef has to have the same name of the property of my class / interface that I am referencing in matCellDef.

According to the Angular Material documentation:

By default, the MatTableDataSource sorts with the assumption that the sorted column's name matches the data property name that the column displays.

For exemple:

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

The name in the matColumnDef directive has to be the same as the name used in the <mat-cell> component.


If the table is inside *ngIf, it won't be working. It will work if it is changed to [hidden]