Angular Reactive Form Disabled Control is not valid

Viewed 4464

I thought that a disabled control would not get validated. But I'm facing this issue.

I have reproduced using the official Angular reactive form sample:

https://stackblitz.com/edit/angular-hyvj24?file=src/app/dynamic-form-question.component.ts

If you type something in the email field and focus out, this will trigger the change event in which I'm doing :

this.form.controls['firstName'].disable();

enter image description here

And although, firstname is NOT a required field, it gets validated and we see a red message. Without this line of code, firstName can be blank and we'll still be able to save.

Why is that ?

1 Answers

When you disabled a control, the control will be valid or not, is the form which is valid although the control is invalid. e.g.

form=new FormGroup({
    control1:new FormControl({value:null,disabled:true},Validators.required),
    control2:new FormControl()
  })

{{form.valid}} //true
{{form.get('control1').valid}}  //false

In your particular case you can change the function isValid for some like:

get isValid() {  
   return this.form.controls[this.question.key].disabled || 
          !this.form.controls[this.question.key].invalid; 
}

Updated Sorry, my bad, in the docs we can see that status can be

  • VALID
  • INVALID
  • PENDING
  • DISABLED

a form control is valid when status is valid -so if status is disabled valid is false. We need use the "oposite" of invalid

get isValid() {  
   return !this.form.controls[this.question.key].invalid; 
}
Related