2
votes

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
you can not, but you can create a custom validator that take account the value of the two controls - Eliseo
I am not sure why everyone is denying it as the Accepted Answer worked for me - codeSays404
The acepted response add a new validator, but you can not remove it if the condition change. I understand you want to add/remove the "required" if you check/uncheck a input type check in your form - Eliseo
Yea, that's a good point. Thanks, I know the accepted solution works only if you want to add Validators which covers my scenario for now but I will keep this in mind - codeSays404

2 Answers

0
votes

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
    ]);
0
votes

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