1
votes

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);
    }
}
  1. formValidators() method is called infinite times - whether am i doing anything wrong here?

  2. 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?

  3. Is it a good approach to bind the method formValidators() in the formGroup?

Help me on this.

1

1 Answers

0
votes
  1. No, its called on each change detection cycle/control change.
  2. Call control.setErrors(null).
  3. The second param expects a function. There is no problem with your code.

The Validator function should return an error object or null. I don't recommend putting your logic inside a validator function as it's not the right place. You can listen to the control1 valueChanges and move the logic to there. This way you'll optimize the code to run only when the control1 value changes.