Disable Validators.Required Angular2

Asked

Viewed 389 times

0

I have the following form using Validators.

 this.formulario = new FormGroup({
    CodigoTemp: new FormControl(null, [Validators.required]),
});

I need to disable Validators.Required if a checkbox is checked. Is there any way to do this?

Utilizo Angular 2.

1 answer

1


You can use the method setValidators, thus:

// Para utilizar uma validação
this.formulario.controls.CodigoTemp.setValidators([
    Validators.required,
]);

// Para remover as validações
this.formulario.controls.CodigoTemp.setValidators(null);

It is worth remembering that this method will replace all existing validations, in case of removing the validations, no problem. If you want to add a new validation, for example, maxLength, should reset existing validations and the new validation you want, thus:

this.formulario.controls.CodigoTemp.setValidators([
    Validators.required,
    Validators.maxLength(50),
]);

As far as I could find, there is still no functionality to add validations, such as discussed here.

  • Thanks @celsomtrindade, it’s exactly what I need and it worked!! However, I need to use this by turning it on and off several times, like this: if(this.todosBairros == true){
 this.formulario.controls.CodigoTemp.setValidators(null);
 }else{
 this.formulario.controls.CodigoTemp.setValidators([
 Validators.required,
 ])
 } However, this way it doesn’t work, you know why?

  • It may be something in the rest of the code. It may be that todosBairros has a different value than expected, or that this call is not executed. It uses console.log to check the values.

  • I ended up discovering that in html had a style lost and when I took it out, everything worked!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.