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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With