Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear validation errors for Angular Material mat-error

I'm trying to reset a form after I've added a value.

Form Code Snippet

<form [formGroup]="addAttributeForm" fxLayout="column">
    <mat-form-field>
      <input matInput formControlName="title" placeholder="Title" required>
      <mat-error>This field is required</mat-error>
    </mat-form-field>
</form>

In the component

onSubmit(form: FormGroup) {
  // do work
  form.reset();
}

What I'm observing:

  1. The form values are set to empty.
  2. But the validation messages are still displayed from mat-error.
  3. I've tried form.markAsPristine(), form.markAsUntouched() and combining all three.

How can I reset the form so the mat-error is not displayed?

like image 322
Richard G Avatar asked Nov 08 '17 14:11

Richard G


People also ask

How do I fix mat form field must contain a Matformfieldcontrol?

To fix the error, add MatInputModule and MatFormFieldModule inside a necessary module or app.

How do you show error in mat form field?

Error messages can be shown under the form field underline by adding mat-error elements inside the form field. Errors are hidden initially and will be displayed on invalid form fields after the user has interacted with the element or the parent form has been submitted.

What is mat in angular material?

The <mat-form-field> is a component that is used to wrap multiple MAT components and implement common text field styles of the form-field such as hint message, underlines, and floating label. These five MAT components are designed to work inside the form-field: <mat-chip-list> <input matNativeControl>


1 Answers

The form group has no "knowledge" about whether the actual HTML form has been submitted or not. It only keeps track of the form values/validity/enabled state. So resetting the form group does reset the values but not any state regarding whether the form has been submitted.

To do this, you need to get a hold of the FormGroupDirective and call resetForm() on it.

Form Code Snippet

<form [formGroup]="addAttributeForm" fxLayout="column">
  <!-- ... -->
</form>

In the component

@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;

onSubmit(form: FormGroup) {
  // do work
  this.formDirective.resetForm();
}
like image 168
Will Howell Avatar answered Sep 24 '22 09:09

Will Howell