From 0f7fbdaa7c872ccecbac4f4ee7851f3d1c2e2f29 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Fri, 1 Dec 2017 19:32:31 +0100 Subject: [PATCH] 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. --- src/cdk/collections/selection.spec.ts | 13 +++++++++++++ src/cdk/collections/selection.ts | 7 ++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/cdk/collections/selection.spec.ts b/src/cdk/collections/selection.spec.ts index 024192f97713..ac89da41ea6e 100644 --- a/src/cdk/collections/selection.spec.ts +++ b/src/cdk/collections/selection.spec.ts @@ -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; let spy: jasmine.Spy; diff --git a/src/cdk/collections/selection.ts b/src/cdk/collections/selection.ts index b03f90672035..4f33ef51986f 100644 --- a/src/cdk/collections/selection.ts +++ b/src/cdk/collections/selection.ts @@ -118,8 +118,11 @@ export class SelectionModel { /** 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); @@ -128,8 +131,6 @@ export class SelectionModel { this._deselectedToEmit = []; this._selectedToEmit = []; } - - this._selected = null; } /** Selects a value. */