Skip to content

Commit 0f7fbda

Browse files
crisbetotinayuangao
authored andcommitted
fix(selection-model): inaccurate selected value when accessed in change subscription (#8599)
Fixes the `selected` value being out of date in the `SelectionModel`, if it is accessed inside an `onChange` subscription. Fixes #8584.
1 parent 7576a73 commit 0f7fbda

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/cdk/collections/selection.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,19 @@ describe('SelectionModel', () => {
102102
expect(event.added).toEqual([2]);
103103
});
104104

105+
it('should have updated the selected value before emitting the change event', () => {
106+
let model = new SelectionModel(true);
107+
let spy = jasmine.createSpy('SelectionModel change event');
108+
109+
// Note: this assertion is only here to run the getter.
110+
expect(model.selected).toEqual([]);
111+
112+
model.onChange!.subscribe(() => spy(model.selected));
113+
model.select(1);
114+
115+
expect(spy).toHaveBeenCalledWith([1]);
116+
});
117+
105118
describe('selection', () => {
106119
let model: SelectionModel<any>;
107120
let spy: jasmine.Spy;

src/cdk/collections/selection.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,11 @@ export class SelectionModel<T> {
118118

119119
/** Emits a change event and clears the records of selected and deselected values. */
120120
private _emitChangeEvent() {
121+
// Clear the selected values so they can be re-cached.
122+
this._selected = null;
123+
121124
if (this._selectedToEmit.length || this._deselectedToEmit.length) {
122-
let eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit);
125+
const eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit);
123126

124127
if (this.onChange) {
125128
this.onChange.next(eventData);
@@ -128,8 +131,6 @@ export class SelectionModel<T> {
128131
this._deselectedToEmit = [];
129132
this._selectedToEmit = [];
130133
}
131-
132-
this._selected = null;
133134
}
134135

135136
/** Selects a value. */

0 commit comments

Comments
 (0)