[Table] MatTableDataSource does not properly sort null/undefined values
See original GitHub issueBug, feature request, or proposal:
Sort of bug, sort of feature request
What is the expected behavior?
rows with undefined values for a sorted column should sort properly
What is the current behavior?
null/undefined values cause random sorting issues
What are the steps to reproduce?
Providing a StackBlitz/Plunker (or similar) is the best way to get the team to see your issue.
Plunker starter (using on @master): https://goo.gl/uDmqyY
StackBlitz starter (using latest npm release): https://goo.gl/wwnhMV
Have a sortable mat-table with some null values in some columns. Try to sort.
What is the use-case or motivation for changing an existing behavior?
columns often have empty values
Which versions of Angular, Material, OS, TypeScript, browsers are affected?
material 5.0.0rc0
Is there anything else we should know?
MatTableDataSource has this line where the actual sorting is done:
return (valueA < valueB ? -1 : 1) * (direction == 'asc' ? 1 : -1);
Note that like values are not treated correctly either. This could be replaced with the following:
return this.compareItems(valueA, valueB) * (direction == 'asc' ? 1 : -1);
private compareItems(itemA: any, itemB: any): number {
let retVal: number = 0;
if (itemA && itemB) {
if (itemA > itemB) retVal = 1;
else if (itemA < itemB) retVal = -1;
}
else if (itemA) retVal = 1;
else if (itemB) retVal = -1;
return retVal;
}
Also, to make strict null safe, the sortingDataAccessor method should be modified to allow such a value.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:10
- Comments:10

Top Related StackOverflow Question
@yedidisatya it has been published with the lastest release so far: https://github.com/angular/material2/releases/tag/5.2.0
Update your library:
And that’s it! 😉
@gangsthub, by upgrading the packing this seems to be not working. I still see the same result while sorting the data when the rows have null/empty or undefined values. Kindly suggest.