I have a requirement for a datatable to be sorted by one column, then by second column. Is there something in Angular Material that supports that? Any help will be highly appreciated.
In the current version of Angular Material there isn't an option for this.
The current version can only look for one active
class within the table headers.
Are you looking for something like the following?
https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/MultipleSorting/Angular/Light/
Since 2020 there is a community addon with MIT-license available that can do multi-sort with mat-table
, in a similar way as the DevExpress component mentioned here in the answer.
In the current version of Angular Material there isn't an option for this.
The current version can only look for one active
class within the table headers.
Are you looking for something like the following?
https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/MultipleSorting/Angular/Light/
There is no a built-in function for multiple sort but you can create your own custom sort function and overwrite the default one.
Check the example code below
export class AppComponent {
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
// override the default sortData with our custom sort function
this.dataSource.sortData = this.customSortData('secondKey');
}
// Init dataSource sort after the view init
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
// custom sort function
customSortData(secondKey: string) {
let sortFunction = (items: Dessert[], sort: MatSort): Dessert[] => {
if (!sort.active || sort.direction === '') {
return items;
}
return sortSensorDataByTwoKeys(
items,
sort.active,
secondKey,
sort.direction
);
};
return sortFunction;
}
}
// Compare logic
function sortSensorDataByTwoKeys(
data: any[],
firstKey: string,
secondKey: string,
orderBy: 'asc' | 'desc' = 'asc'
) {
return data.sort((item1, item2) => {
if (item1[firstKey] === item2[firstKey]) {
let valukeKeyresult =
parseInt(item1[secondKey]) - parseInt(item2[secondKey]);
if (orderBy === 'desc') {
valukeKeyresult =
parseInt(item2[secondKey]) - parseInt(item1[secondKey]);
}
return valukeKeyresult;
}
let firstKeyResult = parseInt(item1[firstKey]) - parseInt(item2[firstKey]);
if (orderBy === 'desc') {
firstKeyResult = parseInt(item2[firstKey]) - parseInt(item1[firstKey]);
}
return firstKeyResult;
});
}
If you want to dynamically change the second key, then you'll need to find a way to achieve it.
The important thing is, with this concept, you could sort the data Source by two key values or even other operations.
© 2022 - 2024 — McMap. All rights reserved.