How to reset Angular form validators
I've spent hours working with Angular forms.
And it's frustrating when your form validation refuses to work properly.
One of those times is when you try to reset the form's controls to "pristine" and "untouched" states, but the validation errors like FormControl.hasError(...)
still persist.
Why do form errors persist after reset?
FormGroup.reset()
resets the form but doesn't clear the validation errors. Especially in Angular Material, the <mat-error>
directive doesn't reset with FormGroup
alone—it checks the validity of FormGroupDirective
.
So the simplest solution is to reset both the form and FormGroupDirective
.
We'll start by adding #formDirective="ngForm"
to your form.
<form [formGroup]="myForm" #formDirective="ngForm" (ngSubmit)="submitForm(myForm, formDirective)">
<mat-form-field>
<input matInput formControlName="email" />
<mat-error *ngIf="email.hasError('required')">Email is required</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" formControlName="password" />
<mat-error *ngIf="password.hasError('required')">Password is required</mat-error>
</mat-form-field>
<button type="submit">Login</button>
</form>
And then inside of our components Typescript file we'll reset both the form and FormGroupDirective
.
private submitForm(formData: any, formDirective: FormGroupDirective): void {
formDirective.resetForm(); // Clears the <mat-error> messages
this.myForm.reset(); // Resets form controls
}
If you don’t want to pass the formDirective
to the function, you can use @ViewChild
in your component.
@ViewChild('formDirective') private formDirective: FormGroupDirective;
private submitForm(): void {
this.formDirective.resetForm(); // Reset the form with validators
this.myForm.reset();
}
So to fully reset your form and clear validation errors, use FormGroupDirective.resetForm()
along with FormGroup.reset()
. This ensures both the form fields and the error messages are cleared effectively.
Now you can easily reset your Angular forms with proper validation states!