Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mat Sort Issue for Numbers and Text Columns

I have angular material datasource. angular material version is ^5.0.3 Sorting is working. However for some columns it is sorting incorrectly. where number and text is there. For instance, sorted result like, 'XXX', '1', '1tesxt', '1', 'OPD', OXD', '12'.

<mat-table #table [dataSource]="dataSource" matSort > 
  <ng-container matColumnDef="model">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Model </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.model}} </mat-cell>
  </ng-container>

Appreciate your help.

like image 748
Roja Fernando Avatar asked Mar 28 '18 06:03

Roja Fernando


Video Answer


1 Answers

This is because the standard sortingDataAccessor casts number strings to number and in Javascript 1 > 'one' and 1 < 'one' both evaluates to false.

As a workaround, you can define your own sortingDataAccessor without the cast:

ngAfterViewInit() {    
  this.dataSource.sort = this.sort;
  this.dataSource.sortingDataAccessor = (data, attribute) => data[attribute];
}

The workaround is copied from this Github issue.

like image 171
Kim Kern Avatar answered Oct 13 '22 19:10

Kim Kern