Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting with dynamic column - Angular material

I am using this URL and I am doing sorting. Sorting is working fine but, I have 2 numeric column

  1. Weight - Its value is coming from DB via API Call and it is present in dataSource. (here, sorting is working)
  2. Double Weight : Its formula is: Weight * 2. Here, "Double weight" is calculated dynamically in HTML and hence it isn't available in datasource.

I need to apply sorting in "Double weight" column. Can someone please guides me on this.

HTML

< ng-container matColumnDef="weight">

< th mat-header-cell *matHeaderCellDef mat-sort-header> Weight

< td mat-cell *matCellDef="let element"> {{element.weight}}

< /ng-container>

< ng-container matColumnDef="weight2">

< th mat-header-cell *matHeaderCellDef mat-sort-header> Weight

< td mat-cell *matCellDef="let element"> {{element.weight * 2}}

< /ng-container>

TS

@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource.sort = this.sort;
}
like image 773
gsr Avatar asked Jul 11 '26 18:07

gsr


1 Answers

I'm pretty sure that sorting on (weight * 2) will give exactly the same result as sorting by weight.

So while you display different values in the two columns, just sort on weight in both cases.

like image 170
Cobus Kruger Avatar answered Jul 13 '26 14:07

Cobus Kruger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!