0

I am not able to sort the column in Mat Table with mat sort having numbers displayed . The numbers returning from the api are comma separated at hundreds , thousands places and so on.

Html

<ng-container matColumnDef="amount">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> Amount </th>
  <td mat-cell *matCellDef="let element"> {{element.amount}} </td>
  <td mat-footer-cell *matFooterCellDef> </td>
</ng-container>

.Ts

displayedColumns: string[] = ['amount', 'name'];

@ViewChild(MatSort) sort: MatSort;

ngOnInit(){
  this.dataSource.sort = this.sort;
}
ngAfterViewInit(){
  this.dataSource.sort = this.sort;
};

naman
  • 51
  • 4

1 Answers1

0

The numbers should be numbers. Use the service to return numbers instead strings using map. e.g. If your property is "amount" you can use your service

getData(id){
  return this.httpClient.get(...).pipe(
    map((x:any)=>({...x,amount:+amount.replace(',','')}))
  )
}
getList(){
  return this.httpClient.get(...).pipe(
    map((res:any[])=>
      return res.map(x=>({...x,amount:+amount.replace(',','')}))
    )
}

Then you can use number pipe to show the number formatted in your table

The other option is add a new property that was number and use this property to sort like this SO (in this SO is used this tecnica to order IPs)

Eliseo
  • 50,109
  • 4
  • 29
  • 67