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();
}
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');
Calling reset on
FormControl
,FormGroup
orFormArray
will only reset the values of native html controls they are attached to. It won't delete the controls from theDOM
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With