Skip to content

Commit

Permalink
fix(table): MatTableDataSource incorrectly sorting zero (angular#10561)
Browse files Browse the repository at this point in the history
Fixes the `MatTableDataSource` sorting zero before negative numbers.

Fixes angular#10556.
  • Loading branch information
crisbeto authored and jelbourn committed Apr 6, 2018
1 parent 6575d9c commit bcb5697
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
6 changes: 3 additions & 3 deletions src/lib/table/table-data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,16 +123,16 @@ export class MatTableDataSource<T> extends DataSource<T> {
// This avoids inconsistent results when comparing values to undefined/null.
// If neither value exists, return 0 (equal).
let comparatorResult = 0;
if (valueA && valueB) {
if (valueA != null && valueB != null) {
// Check if one value is greater than the other; if equal, comparatorResult should remain 0.
if (valueA > valueB) {
comparatorResult = 1;
} else if (valueA < valueB) {
comparatorResult = -1;
}
} else if (valueA) {
} else if (valueA != null) {
comparatorResult = 1;
} else if (valueB) {
} else if (valueB != null) {
comparatorResult = -1;
}

Expand Down
35 changes: 32 additions & 3 deletions src/lib/table/table.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,35 @@ describe('MatTable', () => {
]);
});

it('should sort zero correctly', () => {
// Activate column A sort
dataSource.data[0].a = 1;
dataSource.data[1].a = 0;
dataSource.data[2].a = -1;

// Expect that zero comes after the negative numbers and before the positive ones.
component.sort.sort(component.sortHeader);
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
['Column A\xa0Sorted by a ascending', 'Column B', 'Column C'],
['-1', 'b_3', 'c_3'],
['0', 'b_2', 'c_2'],
['1', 'b_1', 'c_1'],
]);


// Expect that zero comes after the negative numbers and before
// the positive ones when switching the sorting direction.
component.sort.sort(component.sortHeader);
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
['Column A\xa0Sorted by a descending', 'Column B', 'Column C'],
['1', 'b_1', 'c_1'],
['0', 'b_2', 'c_2'],
['-1', 'b_3', 'c_3'],
]);
});

it('should be able to page the table contents', fakeAsync(() => {
// Add 100 rows, should only display first 5 since page length is 5
for (let i = 0; i < 100; i++) {
Expand Down Expand Up @@ -299,9 +328,9 @@ describe('MatTable', () => {
});

interface TestData {
a: string|undefined;
b: string|undefined;
c: string|undefined;
a: string|number|undefined;
b: string|number|undefined;
c: string|number|undefined;
}

class FakeDataSource extends DataSource<TestData> {
Expand Down

0 comments on commit bcb5697

Please sign in to comment.