Currently, I am facing an issue where I need to add or remove validators in a formGroup's controls based on certain conditions. When I try to update the validators using `formGroup.updateValueAndValidity()` for the entire form, it does not seem to work as expected. However, if I individually apply the update for each control like `formGroup.get('formControl').updateValueAndValidity()`, it works fine but this approach doesn't seem ideal as I have to specify it for every control.
if (data == 'x') {
this.myForm.get('control2').setValue(null);
this.myForm.get('control2').setValidators(Validators.nullValidator);
this.myForm.get('control1').setValidators(Validators.required);
} else if (data == 'y') {
this.myForm.get('control1').setValue(null);
this.myForm.get('control1').setValidators(Validators.nullValidator);
this.myForm.get('control2').setValidators(Validators.required);
}
this.myForm.get('control1').updateValueAndValidity();
this.myForm.get('control2').updateValueAndValidity();
Although the above code snippet is functional, when I attempt to update all controls at once using
this.myForm.updateValueAndValidity();
it does not produce the desired result.