Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not lose the initialized Validators after using setValidators Dynamically in Angular?

I have a parent component Where I create a FormControl Array and initialize it with Validations.required Validator.

In Child Component I am adding a Dynamic Validator based on input from parent (true/false) but adding that Validator will remove 'required' from the Control.

How can I keep the initialized and later added Validators in the Form Control?

like image 861
sarfrazanwar Avatar asked May 12 '26 16:05

sarfrazanwar


1 Answers

SetValidators will overwrite the validators with whatever you set. What you need to do is append additional validators keeping the current ones intact. See code below to do this.

    this.<<formControl>>.setValidators([
        this.newValidator(),
        this.<<formControl>>.validator
    ]);
like image 82
Alvin Saldanha Avatar answered May 14 '26 06:05

Alvin Saldanha