Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 reactive form how to reset the form and get its initial values instead of resetting them to empty values

Is there a way to reset a reactive form group into its initial values instead of get it empty using .reset() method ?

I have the following stackblitz, where the default selected value is Parent, and if the user change it to sister, and wants to get the form to initial value, click on reset button to do so.

Currently, I tried:

this.formGroup.reset();
//Or
this.formGroup.markAsPristine;
//Or
this.formGroup.markAsTouched

The .reset() reset the form completly.

P.S. Some people may say that the user can re-select the default value instead of clicking on reset button. But in my case, I have a huge user form where he needs to update his information, and he may needs to reset to initial values if he was mistaken in some values.

like image 943
alim1990 Avatar asked Dec 10 '18 13:12

alim1990


People also ask

How do I reset my reactive form?

How do I reset the reactive form in angular 13? 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.

How would you reset all objects on a form?

If you take a look at the reset button of the first form, Toggle submit, you will notice that it calls a method resetForm() on the click event of the button. Similarly the second form, Always submit, calls a method reset() . Both methods are called on the heroForm object.


1 Answers

You can save the form initial values:

this.initialValues = this.formGroup.value;

And then pass those values to the reset function:

this.formGroup.reset(this.initialValues);
like image 54
Ferares Avatar answered Sep 21 '22 13:09

Ferares