Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mat-table Sorting Demo not Working

People also ask

How do I disable MatSort?

To prevent the user from clearing the sort state from an already sorted column, set matSortDisableClear to true on the matSort to affect all headers, or set disableClear to true on a specific header.

What is MatColumnDef?

MatColumnDef extends CdkColumnDefDefines a set of cells available for a table column.


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]


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.


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