Skip to content

Commit

Permalink
fix(cdk/collections): SelectionModel does not always respect the comp…
Browse files Browse the repository at this point in the history
…areWith function

Fixed bug in SelectionModel where compareWith function was not consistently respected in deselect method.

Fixes angular#25878
  • Loading branch information
FrenchTechLead committed Jan 26, 2023
1 parent b70baab commit 5bc0a41
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
8 changes: 4 additions & 4 deletions src/cdk/collections/selection-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,7 @@ export class SelectionModel<T> {
* Determines whether a value is selected.
*/
isSelected(value: T): boolean {
value = this._getConcreteValue(value);
return this._selection.has(value);
return this._selection.has(this._getConcreteValue(value));
}

/**
Expand Down Expand Up @@ -241,11 +240,12 @@ export class SelectionModel<T> {
return concreteValue;
} else {
this._selection.forEach(selectedValue => {
if (this.compareWith?.call(undefined, inputValue, selectedValue)) {
if (this.compareWith!(inputValue, selectedValue)) {
concreteValue = selectedValue;
return;
}
});
return concreteValue;
return inputValue;
}
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/cdk/collections/selection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,21 +281,21 @@ describe('SelectionModel', () => {
});

it('should deselect value if comparable to another one', () => {
type T = {key: number; value: string};
const v1: T = {key: 1, value: 'blue'};
const v2: T = {key: 1, value: 'green'};
const compareFun = (x: T, y: T) => x.key === y.key;
const model = new SelectionModel<T>(false, [v1], false, compareFun);
type Item = {key: number; value: string};
const v1: Item = {key: 1, value: 'blue'};
const v2: Item = {key: 1, value: 'green'};
const compareFun = (x: Item, y: Item) => x.key === y.key;
const model = new SelectionModel<Item>(false, [v1], false, compareFun);
model.deselect(v2);
expect(model.selected.length).toBe(0);
});

it('should not deselect value if not comparable to another one', () => {
type T = {key: number; value: string};
const v1: T = {key: 1, value: 'blue'};
const v2: T = {key: 2, value: 'apple'};
const compareFun = (x: T, y: T) => x.key === y.key;
const model = new SelectionModel<T>(false, [v1], false, compareFun);
type Item = {key: number; value: string};
const v1: Item = {key: 1, value: 'blue'};
const v2: Item = {key: 2, value: 'apple'};
const compareFun = (x: Item, y: Item) => x.key === y.key;
const model = new SelectionModel<Item>(false, [v1], false, compareFun);
model.deselect(v2);
expect(model.selected.length).toBe(1);
});
Expand Down

0 comments on commit 5bc0a41

Please sign in to comment.