How should I go about conditionally requiring a form field? I made a custom validator, but the conditional variables that I pass to the custom validator are static and remai
Following your comment I can see a potential problem. Since you provide conditions as primitive types to the function that creates the validators function, the values when calling the first one will be used. Even if they change after, the new values won't be taken into account.
To archive that you need to use an object for conditions as described below:
private foo: boolean = false;
private bar: boolean = true;
private conditions: any = {
condition1: foo,
condition2: !bar
};
constructor(private _fb: FormBuilder) {
function conditionalRequired(conditions: any) {
return (control: Control): { [s: string]: boolean } => {
let required: boolean = true;
for (var elt in conditions) {
var condition = conditions[elt];
if (conditions === false) {
required = false;
}
}
if (required && !control.value) {
return { required: true };
}
}
}
this.applyForm = _fb.group({
'firstName': ['', Validators.compose([
conditionalRequired(conditions)
])],
...
});
}
This way the conditions parameter can be used / updated by reference. To update your conditions, you need to do the following:
updateConditions() {
this.conditions.condition1 = true;
this.conditions.condition2 = true;
}
Here is a plunkr: https://plnkr.co/edit/bnX7p0?p=preview.
Edit
To run the validator when updating the conditions, you need to explicitly call the updateValueAndValidity method of the control. In this case, the valid attribute of both control and form will be updated accordingly:
updateConditions() {
this.conditions.condition1 = true;
this.conditions.condition2 = true;
this.applyForm.controls.firstName.updateValueAndValidity();
}