54

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.

4

19 回答 19

62

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();
    }
}
于 2017-05-26T09:55:00.623 回答
19

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

于 2017-07-14T01:41:04.303 回答
7

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
}
于 2020-03-05T12:11:41.170 回答
7
<form #formDirective="ngForm" (ngSubmit)="submitForm(formDirective)">

And in your component class, call formDirective.resetForm():

private submitForm(formDirective): void {
    formDirective.resetForm();
    this.myForm.reset();
}
于 2020-08-04T05:03:44.343 回答
6

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.

于 2016-08-13T07:53:05.863 回答
5

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

于 2016-01-05T09:46:08.107 回答
5

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();
}
于 2019-03-11T02:01:17.090 回答
4

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();
}
于 2017-03-08T09:20:57.360 回答
3

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();
    }
}
于 2018-11-06T12:27:31.073 回答
3

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; 
于 2020-01-09T09:13:04.870 回答
2

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.

于 2018-07-06T10:45:18.403 回答
2

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.

于 2020-07-08T10:59:13.557 回答
1

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();
      });
于 2021-12-16T00:28:17.793 回答
0

if you use model-driven forms i.e ngFormModel, Defining the controlGroup once again after submitting will solve this.Refer this link

于 2016-01-19T18:16:40.857 回答
0

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.

于 2016-05-16T16:17:20.797 回答
0

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();
}
于 2019-09-04T03:38:55.337 回答
0

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.

于 2020-07-14T12:26:53.903 回答
0

Angular Reactive Forms

onCancel(): void {
    this.registrationForm.reset();
    this.registrationForm.controls['name'].setErrors(null);
    this.registrationForm.controls['email'].setErrors(null);
  }
于 2020-12-24T16:25:12.363 回答
-3

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);
于 2020-01-14T14:55:55.410 回答