Mat-table Sorting Demo not Working
Solution 1:
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
Solution 2:
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.
Solution 3:
If the table is inside *ngIf, it won't be working. It will work if it is changed to [hidden]
Solution 4:
matColumnDef name and *matCellDef actual value name should be same
Example:
<ng-container matColumnDef="oppNo">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Opportunity Number</th>
<td mat-cell *matCellDef="let element">{{element.oppNo}}</td>
</ng-container>
In my case oppNo is same for matColumnDef name and *matCellDef name and sorting working fine.
Solution 5:
I also hit this issue. Since you need to wait for the child to be defined, you have to implement and use AfterViewInit
, not onInit.
ngAfterViewInit (){
this.dataSource.sort = this.sort;
}