From 391a9fd5b72780192ef952140d74711424dfda81 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Sat, 5 Jan 2019 00:06:39 +0200 Subject: [PATCH] fix(select): form field state not updated if options are reset (#14720) Fixes the state of the form field around a `mat-select` not being updated when the amount of options changes, causing the value to be updated. Fixes #14709. --- src/lib/select/select.spec.ts | 25 +++++++++++++++++++++++-- src/lib/select/select.ts | 1 + 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/lib/select/select.spec.ts b/src/lib/select/select.spec.ts index b7a26cb0fb7..b6b5526d119 100644 --- a/src/lib/select/select.spec.ts +++ b/src/lib/select/select.spec.ts @@ -2453,6 +2453,22 @@ describe('MatSelect', () => { expect(component.select.errorState).toBe(true); expect(errorStateMatcher.isErrorState).toHaveBeenCalled(); })); + + it('should notify that the state changed when the options have changed', fakeAsync(() => { + testComponent.formControl.setValue('pizza-1'); + fixture.detectChanges(); + + const spy = jasmine.createSpy('stateChanges spy'); + const subscription = testComponent.select.stateChanges.subscribe(spy); + + testComponent.options = []; + fixture.detectChanges(); + tick(); + + expect(spy).toHaveBeenCalled(); + subscription.unsubscribe(); + })); + }); describe('with custom error behavior', () => { @@ -4640,8 +4656,9 @@ class InvalidSelectInForm {
- Steak - Pizza + + {{option.viewValue}} + This field is required @@ -4652,6 +4669,10 @@ class InvalidSelectInForm { class SelectInsideFormGroup { @ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective; @ViewChild(MatSelect) select: MatSelect; + options = [ + {value: 'steak-0', viewValue: 'Steak'}, + {value: 'pizza-1', viewValue: 'Pizza'}, + ]; formControl = new FormControl('', Validators.required); formGroup = new FormGroup({ food: this.formControl diff --git a/src/lib/select/select.ts b/src/lib/select/select.ts index 0d8938d348a..576dead9df8 100644 --- a/src/lib/select/select.ts +++ b/src/lib/select/select.ts @@ -819,6 +819,7 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit, // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value); + this.stateChanges.next(); }); }