Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Table Alphanumeric Sorting Behaviour

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

like image 460
Rich Avatar asked Mar 06 '19 06:03

Rich


Video Answer


3 Answers

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;
});
like image 115
Rich Avatar answered Oct 23 '22 02:10

Rich


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));
like image 22
Ushma Joshi Avatar answered Oct 23 '22 03:10

Ushma Joshi


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

usage:

ngOnInit() {
this.dataSource.data.sort((a, b) => (a.code- b.code) );
  }
like image 30
Amit Baranes Avatar answered Oct 23 '22 03:10

Amit Baranes