60

In an Angular reactive form. How to reset only the state of form after successful submit?

Here is the process:

  • Create the form and setValue from service result
  • Modify values and submit the form
  • If form is properly submitted to service, then reset and keep values

How to keep values as modified and reset the form to its pristine state.

A form.reset() simply empty the form. But if I don't call it, the state is not reset and for example my validations depending on form state classes (pristine, dirty, valid etc.) are still there.

1
  • I usually create a method like initForm, which i call on ngInit, and again after submitting the form
    – mareks
    May 3, 2017 at 12:08

8 Answers 8

101

The solution of @smnbbrv works pretty well.

You can also provide your actual form value to reset() method.

Given the fact myReactiveForm is a Reactive form in your component. After successful submit of your form (by calling a service for example), then your can do:

this.myReactiveForm.reset(this.myReactiveForm.value);

It will reset the form and set the "new" form values to the same value you form had.

This method can be see within Tour of Hero example Official Angular.io doc

4
  • 2
    This is so much a hack :D However, I must admit it should work ;)
    – smnbbrv
    May 3, 2017 at 12:25
  • Yep! We can find amazing solutions by reading Angular doc. These guys are so... brilliant! May 3, 2017 at 12:26
  • Well I'm tired to read it after reading it four times since angular2 beta, so I will leave it to the ones who likes it :) I actually don't find this to be a good solution, because it unnecessarily rewrites all the form values and it might cause performance problems on huge forms.
    – smnbbrv
    May 3, 2017 at 18:47
  • 11
    Tried and this solution does not work. Because reactive form receives latest value from input fields right away, the "this.myReactiveForm.value" passed to the "reset" method does not reflect the prior state of the form, rather it is the latest value on the form. Thus this way of reset results in a no-op. The form under this solution stays unchanged instead of being reverted/reset to a prior state as expected.
    – Yiling
    May 24, 2018 at 20:29
37

That's pretty much easy:

this.form.markAsPristine();
this.form.markAsUntouched();

This resets the form metadata and the form is pristine again

2
  • 1
    Is this removes validation part also?
    – sireesha j
    Nov 1, 2018 at 9:30
  • @sireeshaj depends exactly what you mean. See my answer if you're using angular material controls. Jan 5, 2019 at 3:33
30

Caution for users of @angular/components (material)

There's an added complication if you're using angular material controls, with mat-error to display your errors. Such errors are displayed based on the result of an ErrorStateMatcher (in addition to any *ngIf you may have applied).

The default ErrorStateMatcher displays errors based on a boolean:

isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean 
{
   return !!(control && control.invalid && (control.touched || (form && form.submitted)));
}

So what this means in English is:

If the form has ever been submitted and one if its controls becomes invalid (per validation rules) then the error will be displayed.

This is often not what you want (especially if you're reading this question!).

Looking at the source code - there isn't a way to set submitted = false unless you call resetForm on the ngForm directive (not the FormGroup object). Setting states as pristine or untouched don't reset submitted to false.

If you're using mat-error you may find it easier to create your own ErrorStateMatcher (simple interface) for custom logic if this is an issue.

Note: ErrorStateMatcher is only in angular material - and not a part of standard angular forms.

2
  • tldr: get a template variable from the ngForm directive and pass it to your reset method. Then call resetForm on it.
    – yooloobooy
    Oct 16, 2020 at 16:20
  • 2
    As this answer points out, when in this situation (where validators will show errors on the form when restting the form with FormGroup#reset(), use a template variable <form #login="ngForm" ... > and either pass login template variable to your (ngSubmit)="submit(login)" function and call resetForm() on it. OR to not have to rely on the submit event, use @ViewChild('login') private _loginNgForm: NgForm; and then this._loginNgForm.resetForm();
    – RcoderNY
    Mar 1, 2021 at 10:58
14

04-06-2020: Ionic 5+ and Angular 9+

Just a single line. i.e. this.form.reset();

Resets the FormGroup, marks all descendants are marked pristine and untouched, and the value of all descendants to null.

 form: FormGroup;

 constructor(private formBuilder: FormBuilder, ) { }

  resetTheForm(): void {
    this.form.reset();
  }
0
5

For reactive forms what worked for me when using angular 7: was to use template-driven form and pass it via the form submit handler like so

// component.html
 <form #f="ngForm" [formGroup]="form" (ngSubmit)="onSubmit(f)" novalidate>
 ....
</form>


// component.ts

onSubmit(form: NgForm) {

// reset form here
 form.form.markAsPristine();
 form.resetForm();
}

It will reset the form and the submitted state to default.

4

I used the patch value to clear the reactive form controls. it worked for me. please try the below code.

onClear() {
   this.formGroup.patchValue({
     fieldName: ''
   });
}
2

Adding a another answers, if you have a disabled input in your form, use getRawValue() as a parameter of ngForm.resetForm(). See the sample:

in HTML:

<form
  (ngSubmit)="formSubmit(myForm)"
  #myForm="ngForm"
>
    ...
</form>

in .TS:

formSubmit(myForm: NgForm) {
   myForm.resetForm(myForm.form.getRawValue());
}
2

Some time this.myForm.reset(this.myForm.value); may not reset to initial values So it is better to create a separate function to initialize the form and call it in ngOnInit() and before call this.myForm.reset(this.myForm.value);

ngOnInit(){
  myFormValues();
}

myFormValues() {
  this.myForm= this.fb.group({
      id: ['', Validators.required],
      name: ['', Validators.required],
    });
}

submitForm() {
  // save data
  myFormValues();
  this.myForm.reset(this.myForm.value)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.