HTML code
<div>
<label for=""
>No additional information flag:</label>
<rca-checkbox formControlName="noAdditionalInfoCheckbox" (checkboxChecked)="onCheckboxChecked($event)"></rca-checkbox>
</div>
<div>
<label >No additional information reasons:</label>
<textarea
formControlName="noAdditionalInformationReasons"
id=""
class="form-control"
></textarea>
</div>
TS file
onCheckboxChecked(isChecked): void {
const noAdditionalInfoReasonsControl = this.addNewRequestFormForIndividual.get('noAdditionalInformationReasons');
if (isChecked){
noAdditionalInfoReasonsControl.setValidators(Validators.required);
this.noAddInfoReasonsErrorMessage = "give reason";
}
else {
noAdditionalInfoReasonsControl.clearValidators;
this.noAddInfoReasonsErrorMessage = '';
}
noAdditionalInfoReasonsControl.updateValueAndValidity;
console.log(this.addNewRequestFormForIndividual.valid);
}
If the checkbox is checked, a required validator will be added to the second FormControl and the Add button over the form will be disabled if the form is not valid.
An issue arises where the last console prints true even after setting validators above, and the Add button remains enabled. Additionally, modifying the required field causes the validation state of the form to change - entering and then deleting content from the required field leads to the Add button being disabled and the form becoming invalid.
Even when unchecking the checkbox, the form stays invalid. The use of updateValueAndValidity
does not resolve this issue, prompting further investigation into why this behavior persists.