Srikant
Srikant

Reputation: 139

Angular Material: A required mat-input field does not show error when the parent form is submitted

For the purpose of code re-use and to maintain consistent functionality across my web app, I created an input component in my app whose role is to embed a mat-input in a parent form.

When the mat-input is a required field, the component displays it correctly in the parent form and an error is displayed when a user interacts with the field but does not enter anything. However, no error is displayed when the parent form is submitted without any user interaction with the embedded field. See StackBlitz url below:

https://stackblitz.com/edit/angular-material2-issue-jph57r

I have posted the above as an issue at Angular Material (See: https://github.com/angular/material2/issues/9788) but perhaps I am missing something.

Am I missing something? Is there a workaround?

Upvotes: 1

Views: 1426

Answers (2)

crucifery
crucifery

Reputation: 458

Use markAllAsTouched() method on a form to mark the control and all its descendant controls as touched.

Official Angular API reference

Upvotes: 1

Srikant
Srikant

Reputation: 139

The following workaround was posted by Jefiozie at GitHub. The code loops through all the controls for the form and marks them as touched.

private setFormGroupTouched(formGroup: FormGroup) {
    Object.keys(this.formGroup.controls).forEach(field => {
      const control = this.formGroup.get(field);
      control.markAsTouched({ onlySelf: true });
    });
  }

Upvotes: 1

Related Questions