Use disable with model-driven form
Asked Answered
D

1

25

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

Dentition answered 24/9, 2016 at 22:51 Comment(3)
hey isn't it supposed to be val1: fb.control('', Validators.required) and you gotta change val 2 as well ?Diet
@Diet you can read this: scotch.io/tutorials/…Dentition
it says what I said though. Dunno if I'm out of the loop. Check my answer if it's completely not what you wanted then I'll remove itDiet
F
51

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

Frediafredie answered 25/9, 2016 at 3:17 Comment(4)
OUCH, this is super verbose... I didn't expect a disabled to be so complex! Anyway, it's the best solution I guess! ThanksDentition
Lovely! Saved my time.Craner
Helped me a lot, thank you so much! In my case (and if you want to disable every form field) this.form.disable(); worked perfectly!Rimskykorsakov
how to add multiple validator in this case? with comma-separated or in array?Kruter

© 2022 - 2024 — McMap. All rights reserved.