There is a more generic approch which can be use for multiple purpose, not just this one.
Each time you want to conditionally add the Validators.required to a control you can use this function.
First create this function (in a service should be the best idea because it's generic, so you can use it later with different conditions in a different component, but for the example it's in the same component)
import { FormGroup, Validators } from '@angular/forms';
conditionallyRequiredValidator(masterControlLabel: string, operator: string, conditionalValue: any, slaveControlLabel: string) {
return (group: FormGroup): {[key: string]: any} => {
const masterControl = group.controls[masterControlLabel];
const slaveControl = group.controls[slaveControlLabel];
if (eval(`'${masterControl.value}' ${operator} '${conditionalValue}'`)) {
return Validators.required(slaveControl)
}
slaveControl.setErrors(null);
return null;
}
}
masterControlLabel: the control which will conditionally add the Validators.required to the slaveControl
operator: the operator you want to use to compare the masterControl value with the conditionalValue
conditionalValue: what ever the value you want the masterControl value must match to conditionally add the validator to the slaveControl
slaveControlLabel: the control which will receive (or not) the conditonal Validators.required
Second and finally, add the validator parameter (or validators parameter if mutliple validations need to be done) in your formGroup like this :
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
constructor(
private angularFormBuilder: FormBuilder,
){ }
myFormGroup: FormGroup = this.angularFormBuilder.group({
age: ['', Validators.required],
licenceNo: [''],
}, {validator: conditionallyRequiredValidator('age', '>=', 18, 'licenceNo')});
In this example if the age is strictly over or egal to 18 then the licenceNo control will be conditionally required