0
votes

I am using the mat-table in combination with the mat-sort-header of angular material. But the strange thing is, the sorting works fine on 2 of 6 columns (0 and 4). When sorting the others, one entry is always pulled to the top and the rest stays unsorted or randomly 'ordered'. I hope I can provide enough code to get it solved. The imports are all there and this is basically copy-pasted from https://v5.material.angular.io/components/table/examples.

The table

every other column looks like the one in the snippet

 <mat-table #matTable [dataSource]="dataSource" matSort>
  <ng-container matColumnDef="Status">
   <mat-header-cell *matHeaderCellDef mat-sort-header
....

TypeScript

@ViewChild(MatSort) sort: MatSort;

ngAfterViewInit() {
   this.dataSource.sort = this.sort;
}
ngOnInit() {
   this.dataSource = new MatTableDataSource(this.projectlist); 
}
//no specific code for sorting needed (I think)

I'm sorry for the screenshot being german, but you should see what I mean.

Sorted

enter image description here

Any idea how to fix this?

1
Does your matColumnDef matches your property names of this.projectList?J. S.

1 Answers

6
votes

To get matSortHeader working you need to make sure that your matColumnDef matches the property name of your datasource object. For instance:

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

matColumnDef is status so your row should also have a property with the exact same name:

export class MyDataSet {
 status: string;
}

Otherwise the sort operator cannot do its job. You could also write your own dataAccessor:

  this.datasource.sortingDataAccessor = ((item: MyDataSet, sortHeaderId: string) => {
      // write code to get your property out of item using sortHeaderId
    });

Some further information here: https://material.angular.io/components/table/api#MatTableDataSource