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?– dev-john
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.– celsomtrindade
I ended up discovering that in html had a style lost and when I took it out, everything worked!!
– dev-john