Here is the plnkr for my question: https://plnkr.co/edit/ObTq02rzcTdA6I2W
The important code to focus on is:
this.formGroup = this.formBuilder.group({
dropdown: [null, Validators.required],
textbox: [null, requiredIf(() => this.formGroup.get('dropdown').value == "isRequired")]
});
saveButtonClick () {
this.formGroup.updateValueAndValidity();
console.log("form valid: " + this.formGroup.valid);
}
requiredIf (predicate) {
return ((formControl) => {
if (predicate()) {
return Validators.required
}
return null;
});
}
If you open up the console while running the example code you can see which functions are being called. The predicate passed to requiredIf is only called when the value of the text box changes. I expected it to be called when any field changes, or at least when saveButtonClick() calls updateValueAndValidity() but neither of those things are happening.
How can I trigger the conditional validation to be reevaluated when the save button is clicked?
I would strongly prefer to not subscribe to the value changes event on the dropdown. I'm working with a large form with a lot of conditional validation and it would be best if the code I have now is all that we needed to achieve the desired effect.