Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use disable with model-driven form

Tags:

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

like image 893
ncohen Avatar asked Sep 24 '16 22:09

ncohen


People also ask

What is model driven form?

Template Driven Forms are used to bind the data to the component class using ngModel. We do not need to take the pain of writing code and most of the task is done by Angular itself. There is very less of effort required from the developer to pass information from the component class to the template.


1 Answers

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

like image 188
Harry Ninh Avatar answered Oct 02 '22 13:10

Harry Ninh