I have an issue regarding adding and removing form controls in angular reactive forms.
consilder the following form,
objBasicInformationForm :any = this.objFormBuilder.group({
.
.
.
newField : ['',[]]
checkbox : [false,[]],
dataArray : this.objFormBuilder.array([this.dataArrayForm()])
});
dataArrayForm(){
return this.objFormBuilder.group({
id : ['',[]],
});
}
The field id in the data array is validated via an API. If the value has an error, an Error is added using setError method.
I have a checkbox for dynamically removing and adding the field 'newField'.
The code for adding and removing the field is as follows
whiteBoardCheckHandler(objEvent : any){
if(objEvent.target.checked){
this.objBasicInformationForm.removeControl('newField');
}
else{
this.objBasicInformationForm.addControl('newField', this.objFormBuilder.control('', []));
this.objBasicInformationForm.updateValueAndValidity()
}
}
The issue comes up with this process when the field id in the form array has an error.
Whenever I check/Uncheck the checkbox, the existing error in the field id is removed.
Does anyone know the cause of the issue and how to solve this? Please let me know if you need any further details.
this.objBasicInformationForm.get('dataArray').updateValueAndValidity()after calling it on the form ?this.objBasicInformationForm.updateValueAndValidity(), callthis.objBasicInformationForm.get('dataArray').updateValueAndValidity()