Skip to content

Commit

Permalink
fix(material-experimental/mdc-form-field): ensure validity styling is…
Browse files Browse the repository at this point in the history
… not reset by foundation (#18266)

Currently, whenever the abstract form-field control turns invalid, the
text-field foundation does not know about the validity change. Since it
refreshes the validity upon focus/blur, it could end up accidentally
removing the invalid class. We fix this, by ensuring that the foundation
shares the validity state with the one from the form-field control.
  • Loading branch information
devversion authored and jelbourn committed Jan 26, 2020
1 parent e37b5e5 commit f43e3e8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/material-experimental/mdc-form-field/form-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,12 @@ export class MatFormField implements AfterViewInit, OnDestroy, AfterContentCheck
get: () => this._shouldLabelFloat(),
});

// By default, the foundation determines the validity of the text-field from the
// specified native input. Since we don't pass a native input to the foundation because
// abstract form controls are not necessarily consisting of an input, we handle the
// text-field validity through the abstract form-field control state.
this._foundation.isValid = () => !this._control.errorState;

// Initial focus state sync. This happens rarely, but we want to account for
// it in case the form-field control has "focused" set to true on init.
this._updateFocusState();
Expand Down
15 changes: 15 additions & 0 deletions src/material-experimental/mdc-input/input.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,21 @@ describe('MatMdcInput with forms', () => {
.toBe('true', 'Expected aria-invalid to be set to "true".');
}));

it('should not reset text-field validity if focus changes for an invalid input',
fakeAsync(() => {
// Mark the control as touched, so that the form-field displays as invalid.
testComponent.formControl.markAsTouched();
fixture.detectChanges();
flush();

const wrapperEl = containerEl.querySelector('.mdc-text-field')!;
expect(wrapperEl.classList).toContain('mdc-text-field--invalid');

dispatchFakeEvent(inputEl, 'focus');
dispatchFakeEvent(inputEl, 'blur');
expect(wrapperEl.classList).toContain('mdc-text-field--invalid');
}));

it('should display an error message when the parent form is submitted', fakeAsync(() => {
expect(testComponent.form.submitted).toBe(false, 'Expected form not to have been submitted');
expect(testComponent.formControl.invalid).toBe(true, 'Expected form control to be invalid');
Expand Down

0 comments on commit f43e3e8

Please sign in to comment.