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

Viewed 798

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?

2 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
    ]);

As per official document

Sets the synchronous validators that are active on this control. Calling this overwrites any existing sync validators.

So It is important to keep in mind that by using this method you will overwrite your existing validators so you will need to include all the validators you need/want for the control that you are resetting.

Official Document: https://angular.io/api/forms/AbstractControl#setValidators

Related