Angular Material Table Alphanumeric Sorting Behaviour

孤者浪人 提交于 2019-12-21 12:16:31

问题


I'm having a problem in Angular Material Table, although it is technically correct, but I'm thinking if there's another way around for this.

Let say that I do have 5 codes, F1, F2, F5, F9, F10.

The Angular Material Table ascending sort order of this will be,

F1
F10
F2
F5
F9

But I'm expecting it to be

F1
F2
F5
F9
F10

My html code is here

<table mat-table [dataSource]="model.financingPurposeList" class="mat-elevation-z8" width="100%">

   <ng-container matColumnDef="code">
       <th mat-header-cell *matHeaderCellDef mat-sort-header> Code </th>
       <td mat-cell *matCellDef="let financingPurpose"> {{financingPurpose.code}} </td>
   </ng-container>

   <ng-container matColumnDef="description">
       <th mat-header-cell *matHeaderCellDef> Description </th>
       <td mat-cell *matCellDef="let financingPurpose"> {{financingPurpose.description}} </td>
   </ng-container>

   <tr mat-header-row *matHeaderRowDef="['code', 'description']; sticky: true"></tr>
   <tr mat-row *matRowDef="let row; columns: ['code', 'description'];" (click)="model.selectedFinancingPurpose.toggle(row)"></tr>

</table>

Is there a possible way to do this?

Related Link:

Natural Sorting

Sorting column containing both numbers and strings


回答1:


This isn't the best solution for this, but I created a short and sweet workaround for this. Using the sort predicate function of the array.

// Following the example to the question

financingPurposeList.sort(function(a, b){
   return a.code.length - b.code.length;
});



回答2:


You can achieve that by adding sort function after getting the data.

usage:

ngOnInit() {
this.dataSource.data.sort((a, b) => (a.code- b.code) );
  }



回答3:


You can do something like this.

var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['F1',
'F10',
'F2',
'F5',
'F9'];
console.log(myArray.sort(collator.compare));


来源:https://stackoverflow.com/questions/55016642/angular-material-table-alphanumeric-sorting-behaviour

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