2

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;
}
2
  • Ok, regardless fact that this is without UX purpose because it's just doubled weight... You can sort by weight and it still will be sorted properly. I mean clicking on double weight can sort by weight under the hood because result will be fine and weight is value which you do have. Commented Oct 11, 2018 at 13:09
  • Please tell me where I need to change the code. Commented Oct 11, 2018 at 15:49

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try following code

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

This might work.

Comments

0

You can use the custom sorting function by which you can have numeric sorting.

sort(valueA: any, valueB: any, order: string) {
let comparison = 0;
if (valueB === null) {
  comparison = 1;
} else if (valueA === null) {
  comparison = -1;
} else if (valueA > valueB) {
  comparison = 1;
} else if (valueA < valueB) {
  comparison = -1;
}
return order === 'desc' ? comparison * -1 : comparison;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.