I am trying to add and remove validators in a formGroup
controls based on certain condition.
When I am updating the validators through formGroup.updateValueAndValidity()
for whole form its not updating, where as if I am specifically applying for each Control i.e. formGroup.get('formControl').updateValueAndValidity()
, it is working but i have to write for each control which is i hope not the correct way. What am i doing wrong?
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();
this is working, but,
this.myForm.updateValueAndValidity();
this is not working.
this.myForm.markAllAsTouched();
instead? – Reprimand