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.
3 Answers
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/

- 1,150
- 9
- 28
-
Something more than this. At any given time, you are sorting on just one column, although all columns are sortable. I need to be able to story by one column, keep that sort active, and then sort by second column. For instance, in the link you mentioned above, I need to be able to sory by State, keep that sort active, then sort by City. Is there anything that supports that functionality? – Vin Jan 23 '19 at 22:51
-
Material UI will not do this, as mentioned above. But if you follow this link I posted, this will do what you need. You need to hold down the shift button when selecting the second column. – Web Nexus Jan 23 '19 at 22:52
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.

- 1,144
- 11
- 9
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.

- 31
- 5