How to reset form validation on submission of the form in ANGULAR 2
AngularAngular2 FormsAngular Problem Overview
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.
Angular Solutions
Solution 1 - Angular
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 - Angular
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 - Angular
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
}
Solution 4 - Angular
<form #formDirective="ngForm" (ngSubmit)="submitForm(formDirective)">
And in your component class, call formDirective.resetForm():
private submitForm(formDirective): void {
formDirective.resetForm();
this.myForm.reset();
}
Solution 5 - Angular
There doesn't seem to be support for that yet. A workaround I have seen is to recreate the form after submit which is obviously cumbersome and ugly.
See also
Solution 6 - Angular
I'm doing this in RC.5, I define my form elements in a template.
<form (ngSubmit)="submit(); form.reset()" #form="ngForm">
Passing the form to submit or watching it with ViewChild
didn't work at all, this is good enough for me at the moment.
Solution 7 - Angular
I appreciate everyones answers here. They pointed me in the right direction.
Angular 6 with Angular Material
<form #myForm="ngForm" [formGroup]="formGroup" (ngSubmit)="submit()">
then
@ViewChild('myForm') myForm: NgForm;
formGroup = new FormGroup({...});
submit() {
if (this.formGroup.pristine ||
this.formGroup.untouched ||
!this.formGroup.valid
) {
return;
}
.... do with form data
this.formGroup.reset();
this.myForm.resetForm();
}
Solution 8 - Angular
In more current versions (Angular 2.4.8 in my case) it's easy:
Marks a control as prestine and therefore valid again.
private resetFormControlValidation(control: AbstractControl) {
control.markAsPristine();
control.markAsUntouched();
control.updateValueAndValidity();
}
Solution 9 - Angular
Building up from Benny Bottema's answer, I was able to reset the form including validations using resetForm() in Angular 6.
class YourComponent {
@ViewChild("yourForm")
yourForm: NgForm;
onSubmit(): void {
doYourThing();
this.yourForm.resetForm();
}
}
Solution 10 - Angular
This Solution in Angular 8 worked for me in Reactive Forms
Name your Form something like this
<form #regForm="ngForm">
Create Object of UI Form using ViewChild
@ViewChild('regForm', {static: false}) myForm: NgForm;
use this, after submit call.
this.myForm.resetForm();
submitted false your validations
this.submitted = false;
Solution 11 - Angular
This worked for me in Angular 5 using template driven forms (it will not work for reactive forms)
<form #myForm = "ngForm" (submit)="callMyAPI(); myForm.resetForm()">
This resets both form values and validations.
Solution 12 - Angular
On resetting by using YourformName.reset()
I was facing validation error issues.
So use YourformName.resetForm()
in your .ts file . It is working correctly now.
I am using template driven form in Angular btw.
Solution 13 - Angular
Just loop over the form controls and make them pristine
(Object as any).values(this.mainForm.form.controls).forEach((control: FormControl) => {
control.markAsUntouched();
control.markAsPristine();
});
Solution 14 - Angular
if you use model-driven forms i.e ngFormModel, Defining the controlGroup once again after submitting will solve this.Refer this link
Solution 15 - Angular
I've recently considered this as there is currently (May 2016) nothing architected into Angular2 for this as yet.
Considering the user cannot enter 'undefined' or 'null' and the validation is mainly used to display form errors to the user then just reset the control values to Null
myControl.updateValue(null);
You will need to add this condition when deciding to display the control errors in your UI simply by adding
if (myControl.value !== undefined && myControl.value !== null) {
//then there is reason to display an error
}
(this check because Validators.Required treats blank content as valid)
Hope this helps.
Solution 16 - Angular
If you are using Angular Material and using <mat-error>
, only way it worked for me is this.
You have to use FormGroupDirective.
@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;
submitBtnClick() {
this.formDirective.resetForm();
}
Solution 17 - Angular
In the latest Angular versions you just need to run this.form.reset()
(it marks everything as pristine and untouched and all that stuff under the hood) and then update value and validity for all the child form controls/groups/arrays.
Unfortunately, there's no direct way to do this for the nested controls without manual children traversal, at least for now.
Solution 18 - Angular
Angular Reactive Forms
onCancel(): void {
this.registrationForm.reset();
this.registrationForm.controls['name'].setErrors(null);
this.registrationForm.controls['email'].setErrors(null);
}
Solution 19 - Angular
Angular 8 Form reset validation errors
Create form:
this.userForm = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(2)]],
email: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')]]});
Reset form:
this.userForm.reset();
this.userForm.controls.userEmail.setErrors(null);