Use disable with model-driven form

ncohen picture ncohen · Sep 25, 2016 · Viewed 27.1k times · Source

I'm trying to use the disabled inside my model-driven form. I have the following form:

this.form = this.formBuilder.group({
    val1: ['', Validators.required],
    val2: [{value:'', disabled:this.form.controls.val1.valid}]
});

I'm getting an error (not finding controls of this.form) probably because I'm using this.form inside this.form.

How can I fix that?

PS I've also tried to add [disabled]='...' inside my html but I get a warning saying I should use the formBuilder instead

Answer

Harry Ninh picture Harry Ninh · Sep 25, 2016

Yea you're right that the problem is because you are referencing a variable (this.form) when it's not initiated yet. Lucky, in your case, you don't really need to refer to the form group in your val2 form control. Your code can be rewritten as followed:

let val1Control = this.formBuilder.control('', Validators.required);
this.form = this.formBuilder.group({
    val1: val1Control ,
    val2: [{value:'', disabled: val1Control.valid}]
});

However, this block only initiates the disabled value of val2 control without monitoring val1Control's validity. To do that, you will need to subscribe to val1Control.statusChanges:

let val1Control = this.formBuilder.control('', Validators.required);
let val2Control = this.formBuilder.control({value:'', disabled: !val1Control.valid});
this.form = this.formBuilder.group({
  val1: val1Control,
  val2: val2Control
})

val1Control.statusChanges.subscribe((newStatus) => {
  if (val1Control.valid) {
    val2Control.enable();
  } else {
    val2Control.disable();
  }
});

Here's the working plunker: http://plnkr.co/edit/kEoX2hN9UcY4yNS3B5NF