'Angular ReactiveForm - form stays valid even after add required (by addValidators) to one formControl

In my ReactiveForm form, I add required validator to one formControl by condition.

if(condition) setRequired();

setRequired() { this.form.get(['company','id']).addValidators(Validators.required);}

but form.valid is true, even the field is empty.

Do I need to add something else?

Thanks.



Solution 1:[1]

After remove/add validator to your form element, you have to invoke function with updateValueAndValidity to update the state.

Like: this.form.updateValueAndValidity();

Or: this.form.get(['company','id']).updateValueAndValidity();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1