Angular Material Table Alphanumeric Sorting Behavi

2020-07-09 09:23发布

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

3条回答
Root(大扎)
2楼-- · 2020-07-09 09:47

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楼-- · 2020-07-09 10:03

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;
});
查看更多
闹够了就滚
4楼-- · 2020-07-09 10:09

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

查看更多
登录 后发表回答