Skip to content

Commit 58627c4

Browse files
authored
fix(table): empty string should be sorted right (#8011)
* fix(table): empty string should be sorted right * newline
1 parent cc4fc11 commit 58627c4

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/lib/table/table-data-source.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,14 @@ export class MatTableDataSource<T> implements DataSource<T> {
8888
* @param sortHeaderId The name of the column that represents the data.
8989
*/
9090
sortingDataAccessor = (data: T, sortHeaderId: string): string|number => {
91-
const value: number|string = data[sortHeaderId];
91+
const value: any = data[sortHeaderId];
92+
93+
// If the value is a string and only whitespace, return the value.
94+
// Otherwise +value will convert it to 0.
95+
if (typeof value === 'string' && !value.trim()) {
96+
return value;
97+
}
98+
9299
return isNaN(+value) ? value : +value;
93100
}
94101

src/lib/table/table.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,21 @@ describe('MatTable', () => {
187187
]);
188188
});
189189

190+
it('should by default correctly sort an empty string', () => {
191+
// Activate column A sort
192+
dataSource.data[0].a = ' ';
193+
component.sort.sort(component.sortHeader);
194+
fixture.detectChanges();
195+
196+
// Expect that empty string row comes before the other values
197+
expectTableToMatchContent(tableElement, [
198+
['Column A\xa0Sorted by a ascending', 'Column B', 'Column C'],
199+
['', 'b_1', 'c_1'],
200+
['a_2', 'b_2', 'c_2'],
201+
['a_3', 'b_3', 'c_3'],
202+
]);
203+
});
204+
190205
it('should be able to page the table contents', fakeAsync(() => {
191206
// Add 100 rows, should only display first 5 since page length is 5
192207
for (let i = 0; i < 100; i++) {

0 commit comments

Comments
 (0)