From ec6678df218383c2f5d3bc36e393b98d04c766f2 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 23 Jan 2018 17:02:49 +0100 Subject: [PATCH] fix(input): floating label not reacting when patching the value without emitting an event (#9260) Fixes the input's floating label state not being updated when the consumer patches the form control's value without emitting an event. Fixes #8982. --- src/lib/input/input.spec.ts | 20 +++++++++++++++++++- src/lib/input/input.ts | 9 +++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/lib/input/input.spec.ts b/src/lib/input/input.spec.ts index a74de097c75..8b384c3a7d7 100644 --- a/src/lib/input/input.spec.ts +++ b/src/lib/input/input.spec.ts @@ -1130,6 +1130,21 @@ describe('MatInput with forms', () => { expect(el).not.toBeNull(); expect(el.classList.contains('mat-form-field-empty')).toBe(false); })); + + it('should update when the form field value is patched without emitting', fakeAsync(() => { + const fixture = TestBed.createComponent(MatInputWithFormControl); + fixture.detectChanges(); + + const el = fixture.debugElement.query(By.css('label')).nativeElement; + + expect(el.classList).toContain('mat-form-field-empty'); + + fixture.componentInstance.formControl.patchValue('value', {emitEvent: false}); + fixture.detectChanges(); + + expect(el.classList).not.toContain('mat-form-field-empty'); + })); + }); @Component({ @@ -1183,7 +1198,10 @@ class MatInputPlaceholderElementTestComponent { } @Component({ - template: `` + template: ` + + + ` }) class MatInputWithFormControl { formControl = new FormControl(); diff --git a/src/lib/input/input.ts b/src/lib/input/input.ts index f2c93ca23e0..e5a518a2724 100644 --- a/src/lib/input/input.ts +++ b/src/lib/input/input.ts @@ -229,11 +229,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< // error triggers that we can't subscribe to (e.g. parent form submissions). This means // that whatever logic is in here has to be super lean or we risk destroying the performance. this.updateErrorState(); - } else { - // When the input isn't used together with `@angular/forms`, we need to check manually for - // changes to the native `value` property in order to update the floating label. - this._dirtyCheckNativeValue(); } + + // We need to dirty-check the native element's value, because there are some cases where + // we won't be notified when it changes (e.g. the consumer isn't using forms or they're + // updating the value using `emitEvent: false`). + this._dirtyCheckNativeValue(); } focus() { this._elementRef.nativeElement.focus(); }