Home > Mobile >  How can i add/remove validators conditionally in reactive forms?
How can i add/remove validators conditionally in reactive forms?

Time:05-31

I have a reactive form like this

this.form = this.formBuilder.group({
  ...
  email: [],
  receiveNewsletter: [],
  ...
})

I want all fields to be optional, except if user checks receiveNewsletter, the email field should be required. How can i do that?

CodePudding user response:

You have to watch the value of the checkbox and add or remove the required validator based on the value of receiveNewsletter

this.form.controls.receiveNewsletter.valueChanges.subscribe(value => {
   if(value){
      this.form.controls.email.addValidators(Validator.required);
   } else {
      this.form.controls.email.removeValidators(Validator.required);
   }
   this.form.controls.email.updateValueAndValidity(); //remember to add this to update the form control state
})
  • Related