Richard G
Richard G

Reputation: 5683

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?

Upvotes: 16

Views: 20715

Answers (3)

This solution works with me. You need to do next:

formReset(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

This reset the form and clear all error.

Upvotes: 10

Will Howell
Will Howell

Reputation: 3715

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();
}

Upvotes: 29

Jared
Jared

Reputation: 2096

The only way I've been able to successfully do this is by setting a flag to hide the form when you want to reset it and then using a timeout to set that flag back to true. As far as I know, there is no built-in way to do this yet.

showForm = true;

reset(): void {
    this.showForm = false;
    setTimeout(() => this.showForm = true);
}

And then in the HTML on the form element use *ngIf="showForm".

Upvotes: 0

Related Questions