How to reset form validation on submission of the form in ANGULAR 2
I have to reset my form along with validation. is there any method to reset the state of form from ng-dirty to ng-pristine.
Solution 1:
Here's how it currently works with Angular 4.1.0 - 5.1.3:
class YourComponent {
@ViewChild("yourForm")
yourForm: NgForm;
onSubmit(): void {
doYourThing();
// yourForm.reset(), yourForm.resetForm() don't work, but this does:
this.yourForm.form.markAsPristine();
this.yourForm.form.markAsUntouched();
this.yourForm.form.updateValueAndValidity();
}
}
Solution 2:
from.resetForm()
I've tried pretty much everything, and the only thing I found that actually resets form.submitted to false is the following:
In your template, send your form into the submit function:
<form name="form" class="form-horizontal" (ngSubmit)="f.form.valid && submit(f)" #f="ngForm" novalidate>
In your component.ts file, have the following:
// import NgForm
import { NgForm } from '@angular/forms';
// get the passed in variable from the html file
submit(myForm: NgForm): void {
console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);
// This is the key!
myForm.resetForm();
console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);
}
The console.log values output the following - notice it resets all values.
VALID true false false true true false false
INVALID false true true false false true true
Solution 3:
app.component.html
The #formDirective="ngForm"
and passing the formDirective
to the onSubmit
method is crucial for resetting error styles such as mat-error
. Check #4190 to follow this bug and in-depth explanation why it's needed and how it works under the hood.
<form [formGroup]="contactForm" (ngSubmit)="onSubmit(contactForm.value, formDirective)" #formDirective="ngForm">
<!-- Your input elements... -->
<button [disabled]="!contactForm.valid">Submit</button>
</form>
app.component.ts
Remember about the FormGroupDirective
which you need to import from @angular/forms
(Angular/Material 9). To make the form empty call this.contactForm.reset();
and the form will be invalid
, it's fine. However, you also need to reset the undesired validators styles, and this is a different method, i.e. formDirective.resetForm();
.
Notice difference between formDirective
and formData
with its different built-in methods.
import { FormGroupDirective } from '@angular/forms';
public contactForm: FormGroup = this.formBuilder.group({
// Your input elements...
});
public onSubmit(
formData: FormGroup,
formDirective: FormGroupDirective
): void {
this.contactForm.reset(); // Reset form data
formDirective.resetForm(); // Reset the ugly validators
}