Mat Sort Issue for Numbers and Text Columns

冷暖自知 提交于 2020-07-20 17:37:04

问题


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.


回答1:


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.




回答2:


You need to take out those characters that are not numbers and convert the string that is holding the numeric characters to a numeric type value.

Your initial column value: 'ID0239'. After taking out the characters: '0239'. After converting the string to number: 0239.

And 0239 is the value you need to return inside the sortingDataAccessor function.



来源:https://stackoverflow.com/questions/49527784/mat-sort-issue-for-numbers-and-text-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!