From db72b06b974182e6398e6c0e18b8a584e5a1b031 Mon Sep 17 00:00:00 2001 From: Will Howell Date: Tue, 23 May 2017 16:55:25 -0400 Subject: [PATCH] fix(select): deselect old options when programmatically setting value (#4658) * fix(select): deselect old options when programmatically setting value * Review changes * Fix lint issues: line length --- src/lib/select/select.spec.ts | 35 +++++++++++++++++++++++++++++++++++ src/lib/select/select.ts | 7 ++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/lib/select/select.spec.ts b/src/lib/select/select.spec.ts index b65c0cc0aed..2b0d6796b98 100644 --- a/src/lib/select/select.spec.ts +++ b/src/lib/select/select.spec.ts @@ -328,6 +328,41 @@ describe('MdSelect', () => { expect(optionInstances[2].selected).toBe(false); }); + it('should deselect other options when one is programmatically selected', () => { + let control = fixture.componentInstance.control; + let foods = fixture.componentInstance.foods; + + trigger.click(); + fixture.detectChanges(); + + let options = + overlayContainerElement.querySelectorAll('md-option') as NodeListOf; + + options[0].click(); + fixture.detectChanges(); + + control.setValue(foods[1].value); + fixture.detectChanges(); + + trigger.click(); + fixture.detectChanges(); + + options = + overlayContainerElement.querySelectorAll('md-option') as NodeListOf; + + expect(options[0].classList) + .not.toContain('mat-selected', 'Expected first option to no longer be selected'); + expect(options[1].classList) + .toContain('mat-selected', 'Expected second option to be selected'); + + const optionInstances = fixture.componentInstance.options.toArray(); + + expect(optionInstances[0].selected) + .toBe(false, 'Expected first option to no longer be selected'); + expect(optionInstances[1].selected) + .toBe(true, 'Expected second option to be selected'); + }); + it('should remove selection if option has been removed', async(() => { let select = fixture.componentInstance.select; diff --git a/src/lib/select/select.ts b/src/lib/select/select.ts index 3bcf2240c03..107dd980331 100644 --- a/src/lib/select/select.ts +++ b/src/lib/select/select.ts @@ -555,12 +555,13 @@ export class MdSelect implements AfterContentInit, OnDestroy, OnInit, ControlVal throw getMdSelectNonArrayValueError(); } + this._clearSelection(); + if (isArray) { - this._clearSelection(); value.forEach((currentValue: any) => this._selectValue(currentValue)); this._sortValues(); - } else if (!this._selectValue(value)) { - this._clearSelection(); + } else { + this._selectValue(value); } this._setValueWidth();