Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormArray length does not reset by form.reset()

I am working on Angular forms data driven approach, I added form controls dynamically to FormArray, I used form.reset() to reset the added controls, but form.reset() doest not reset the FormArray length, I have found that this is a known issue and can be solved using this approach, https://github.com/angular/angular/pull/11051 , but still I am unclear about this. Please help, Thanks

reviewForm: FormGroup;
  ngOnInit(){
    this.reviewForm = new FormGroup({            
      'controlArray': new FormArray([        
    ])
    });
  }

onSubmit(){     
    this.formData = new FormData(this.formService.formName, this.reviewForm.value.controlArray);    
    let formControls = JSON.stringify(this.formData); 
    // console.log(formControls);
    this.formService.createForm(formControls)
      .subscribe(
        data => console.log(data),
        error => console.error(error)
    );
    this.reviewForm.reset();    
  }
like image 331
Waleed Shahzaib Avatar asked Nov 21 '17 08:11

Waleed Shahzaib


2 Answers

Another approach would be to clear the array and add add when necessary a default array element, e.g.:

// All array elements are removed
(this.reviewForm.get('controlArray') as FormArray).clear();
// Other values are removed
this.reviewForm.reset();
// When necessary add an initial array element
// (this.reviewForm.get('controlArray') as FormArray).push(new FormControl('Initial Element');
like image 41
Kevin Wallis Avatar answered Oct 11 '22 20:10

Kevin Wallis


Calling reset on FormControl, FormGroup or FormArray will only reset the values of native html controls they are attached to. It won't delete the controls from the DOM.

Only way you can add controls to a FormArray is via your component code file (typescript) dynamically. That means you will update the DOM dynamically. Hence, calling reset on the FormArray will only clear the values of the dynamically added controls (set the controls to their initial state. Empty string for a input box for example). On the other hand, resetting the length of the FromArray requires deleting all the controls inside the FormArray.

So in this case you will have to set the FormArray control itself with an empty FormArray. Consider the following example which deletes all the controls of a FormArray by replacing it with an empty FormArray instance,

this.reviewForm.setControl('controlArray', new FormArray([]));

When using with a FormBuilder instance you can do it like the following,

this.reviewForm.setControl('controlArray', this.fb.array([])); // here, `fb` is a form builder instance 
like image 53
Fiyaz Hasan Avatar answered Oct 11 '22 18:10

Fiyaz Hasan