Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactive forms : how to reset form state and keep values after submit

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.

like image 702
ExaPsa Avatar asked May 03 '17 12:05

ExaPsa


People also ask

How do you reset the form after submit in angular?

import { FormsModule } from '@angular/forms'; In Reactive forms, we need to import FormGroup from '@angular/forms' . After importing the above-mentioned modules in the respective approach, angular forms module provides an inbuilt method called reset(). We can use the method and we can reset the form.

What does Formcontrol Reset do?

reset()linkResets the form control, marking it pristine and untouched , and resetting the value. The new value will be the provided value (if passed), null , or the initial value if nonNullable was set in the constructor via FormControlOptions .

How would you reset all objects on a form in angular?

In a model-driven form to reset the form we just need to call the function reset() on our myform model. The form now resets, all the input fields go back to their initial state and any valid , touched or dirty properties are also reset to their starting values.


1 Answers

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

like image 153
BlackHoleGalaxy Avatar answered Sep 17 '22 15:09

BlackHoleGalaxy