Skip to content

Commit ec6678d

Browse files
crisbetojelbourn
authored andcommitted
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.
1 parent 48bf0ed commit ec6678d

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

src/lib/input/input.spec.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,21 @@ describe('MatInput with forms', () => {
11301130
expect(el).not.toBeNull();
11311131
expect(el.classList.contains('mat-form-field-empty')).toBe(false);
11321132
}));
1133+
1134+
it('should update when the form field value is patched without emitting', fakeAsync(() => {
1135+
const fixture = TestBed.createComponent(MatInputWithFormControl);
1136+
fixture.detectChanges();
1137+
1138+
const el = fixture.debugElement.query(By.css('label')).nativeElement;
1139+
1140+
expect(el.classList).toContain('mat-form-field-empty');
1141+
1142+
fixture.componentInstance.formControl.patchValue('value', {emitEvent: false});
1143+
fixture.detectChanges();
1144+
1145+
expect(el.classList).not.toContain('mat-form-field-empty');
1146+
}));
1147+
11331148
});
11341149

11351150
@Component({
@@ -1183,7 +1198,10 @@ class MatInputPlaceholderElementTestComponent {
11831198
}
11841199

11851200
@Component({
1186-
template: `<mat-form-field><input matInput [formControl]="formControl"></mat-form-field>`
1201+
template: `
1202+
<mat-form-field>
1203+
<input matInput placeholder="Hello" [formControl]="formControl">
1204+
</mat-form-field>`
11871205
})
11881206
class MatInputWithFormControl {
11891207
formControl = new FormControl();

src/lib/input/input.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,11 +229,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl<
229229
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
230230
// that whatever logic is in here has to be super lean or we risk destroying the performance.
231231
this.updateErrorState();
232-
} else {
233-
// When the input isn't used together with `@angular/forms`, we need to check manually for
234-
// changes to the native `value` property in order to update the floating label.
235-
this._dirtyCheckNativeValue();
236232
}
233+
234+
// We need to dirty-check the native element's value, because there are some cases where
235+
// we won't be notified when it changes (e.g. the consumer isn't using forms or they're
236+
// updating the value using `emitEvent: false`).
237+
this._dirtyCheckNativeValue();
237238
}
238239

239240
focus() { this._elementRef.nativeElement.focus(); }

0 commit comments

Comments
 (0)