0

I am working on Angular 5 app and using FormArray of reactive forms. when user make some changes in one or more FormGroup and later change his mind and click on "Cancel change" button than how to restore the initial state of component Model??

I tried looking for this on the angular official website and on stackOverflow but did not find anything similar to this.

Akash
  • 848
  • 1
  • 11
  • 30

3 Answers3

0

You need to have original form object state.

let original = {
   fname: '',
   lname: '',
   date: ''
};

Take a copy from original object

let copied = Object.assign({}, original);

You can use the copied object inside the Form Group & Form Array.

When click reset, you can use original object.

Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
  • I do have a original copy save in another varaible as you have mentioned. but can you elaborate on "When click reset, you can use original object." ?? I mean, I do not think, we can pass the original modal to the reset API of FormArray? can we ? – Akash Sep 27 '18 at 10:13
  • What i mean is, you can assign the copied object = original. when we click reset. i.e copied = Object.assign({}, original); – Suresh Kumar Ariya Sep 27 '18 at 11:40
0

This is how you reset:

const originalState = {foo: 'bar'};

public myForm = this.fb.group(originalState);

resetMyForm() {
  this.myForm.reset(originalState);
}

Calling just reset() will set all controls to null.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
0

Somehow, the reset function was not what I was looking for so I end-up using the below function for reseting the formarray,

purgeForm(form: FormArray) {
    while (0 !== form.length) {
      form.removeAt(0);
    }
  }
Akash
  • 848
  • 1
  • 11
  • 30