I have a simple yet perplexing problem. I have a reactive form and I want to set validation programatically.
this.boatForm.get('boatType').setValidators(Validators.required);
this.boatForm.updateValueAndValidity();
this.boatForm.get('boatType').updateValueAndValidity();
this.#logger.debug(
'/n', 'value:', this.boatForm.get('boatType').value,
'/n', 'valid:', this.boatForm.get('boatType').valid
)
The value of the boatType control is null. Therefore I expect the log to show:
value: valid: false
And... it does.
But I have multiple controls on that form so instead of applying updateValueAndValidity() to each control individually, I want to execute:
this.boatForm.get('boatType').setValidators(Validators.required);
// Set other validators on other controls on the same form
this.boatForm.updateValueAndValidity();
this.#logger.debug(
'\n', 'value', this.boatForm.get('boatType').value,
'\n', 'valid', this.boatForm.get('boatType').valid
)
But now, I get:
value: valid: true
The work-around that we have implemented is to call a method:
static updateFormControlValidators(form: FormGroup): void {
// Iterate over each control in the form group
Object.keys(form.controls).forEach(controlName => {
const control = form.get(controlName);
// Call updateValueAndValidity to re-evaluate the validity of each control
if (control) {
control.updateValueAndValidity();
}
});
}
But the question is:
Should form.updateValueAndValidity() accomplish the same thing?