Trying to add a validator depending on some condition. When the condition is true i am adding required validator and removing it when it is false.
createReactiveForm(data: any) {
const formGroup = new FormGroup({
'control1': new FormControl(data.key1),
'control2': new FormControl(data.key2)
}, this.formValidators.bind(this)),
}
formValidators(formGroup: FormGroup){
const control1Val: boolean = formGroup.controls['control1'].value;
if (control1Val) {
const control2: AbstractControl = formGroup.controls['control2'];
constrol2.setValidators(Validators.required);
} else {
const control2: AbstractControl = formGroup.controls['control2'];
constrol2.setValidators(() => null);
}
}
formValidators() method is called infinite times - whether am i doing anything wrong here?
When the condition is true it is adding validators and displaying the error.But when the condition is false, validators are removed, but error on the control still exists - what is the reason?
Is it a good approach to bind the method formValidators() in the formGroup?
Help me on this.