Skip to content

Commit

Permalink
fix(selection-model): inaccurate selected value when accessed in chan…
Browse files Browse the repository at this point in the history
…ge subscription (#8599)

Fixes the `selected` value being out of date in the `SelectionModel`, if it is accessed inside an `onChange` subscription.

Fixes #8584.
  • Loading branch information
crisbeto authored and tinayuangao committed Dec 1, 2017
1 parent 7576a73 commit 0f7fbda
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
13 changes: 13 additions & 0 deletions src/cdk/collections/selection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,19 @@ describe('SelectionModel', () => {
expect(event.added).toEqual([2]);
});

it('should have updated the selected value before emitting the change event', () => {
let model = new SelectionModel(true);
let spy = jasmine.createSpy('SelectionModel change event');

// Note: this assertion is only here to run the getter.
expect(model.selected).toEqual([]);

model.onChange!.subscribe(() => spy(model.selected));
model.select(1);

expect(spy).toHaveBeenCalledWith([1]);
});

describe('selection', () => {
let model: SelectionModel<any>;
let spy: jasmine.Spy;
Expand Down
7 changes: 4 additions & 3 deletions src/cdk/collections/selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@ export class SelectionModel<T> {

/** Emits a change event and clears the records of selected and deselected values. */
private _emitChangeEvent() {
// Clear the selected values so they can be re-cached.
this._selected = null;

if (this._selectedToEmit.length || this._deselectedToEmit.length) {
let eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit);
const eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit);

if (this.onChange) {
this.onChange.next(eventData);
Expand All @@ -128,8 +131,6 @@ export class SelectionModel<T> {
this._deselectedToEmit = [];
this._selectedToEmit = [];
}

this._selected = null;
}

/** Selects a value. */
Expand Down

0 comments on commit 0f7fbda

Please sign in to comment.