4

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.

11
  • Have you tried calling this.objBasicInformationForm.get('dataArray').updateValueAndValidity() after calling it on the form ? Commented Jul 13, 2022 at 12:26
  • @temp_user , do you mean that I need to call the same after adding/removing new control or adding the error to the field? Commented Jul 13, 2022 at 12:29
  • Just after this.objBasicInformationForm.updateValueAndValidity(), call this.objBasicInformationForm.get('dataArray').updateValueAndValidity() Commented Jul 13, 2022 at 12:30
  • @temp_user Tried, Not working Commented Jul 13, 2022 at 12:32
  • 1
    @VinceCyriac you don't need to remove the validations, just set it as disabled and the validations wont trigger Commented Jul 13, 2022 at 12:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.