12
votes

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.

4
Why not adding this.formGroup.get('family_relation').setValue(1) at the end of reset() method? - Maihan Nijat
It is a form control array with several rows and multiple form control. I think it is not a good idea to set manually the value of each of them - alim1990

4 Answers

21
votes

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);
4
votes

Please find the stackbliz here

https://stackblitz.com/edit/angular-material-ciztu9

Angular Provides reset(formState:any = null), you can pass the initial formState/object as a first parameter

For more info https://angular.io/api/forms/FormControl#reset

1
votes

Create a method setForm() which will be called in the constructor and reset()

setForm() {
  this.formGroup = this.fb.group({
    'family_relation': new FormControl(this.familyRelationArray[0]['family_relation_id'])
  });
}

(Remove the code from the constructor which set the initial values)

resetForm() now looks like:

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

    this.setForm();
  }

And the constructor:

constructor(private fb: FormBuilder) {

    this.familyRelationArray = [
      {
        family_relation_id: 1,
        family_relation_type: 'Parent'
      },
      {
        family_relation_id: 2,
        family_relation_type: 'Sister'
      }
    ];
    this.setForm();

  }
0
votes

There might be other ways of doing it, but I would do it using one of following methods:

Method 1: Passing values to the reset method.

reset() {
  this.formGroup.reset({family_relation: 1});
  //Or
  this.formGroup.markAsPristine;
  //Or
  this.formGroup.markAsTouched;
}

Method 2: Setting values

reset() {
  this.formGroup.reset();
  //Or
  this.formGroup.markAsPristine;
  //Or
  this.formGroup.markAsTouched;
  // this.formGroup.get('family_relation').setValue(1)
}