Up until "final" 2.0 of Angular I have done this:
<input type="text" formControlName="name" [disabled]="!showName">
To dynamically disable/enable form inputs.
After upgrading from Rc7 to 2.0 I get this warning in the console window:
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors.
I have changed my code to follow these instructions like this:
this._userGroupUsersForm = this._formBuilder.group({ 'users': [{'', disabled: this.showName}, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50), Validators.pattern("^[a-zA-ZåäöÅÄÖ 0-9_-]+$")])] });
And that works fine for the initial page load, but I can no longer toggle the status like this:
toggleName() : void { this.showName = !this.showName; }
How do I solve this?
Note: My "old" way of doing this (by setting [disabled]) doesn't work any more either.
The ng-disabled directive sets the disabled attribute of a form field (input, select, or textarea). The form field will be disabled if the expression inside the ng-disabled attribute returns true. The ng-disabled directive is necessary to be able to shift the value between true and false .
This same issue had me pulling my hair. My solution was to use interpolation rather than one-way binding to update the property. In your case, instead of using:
<input type="text" formControlName="name" [disabled]="!showName">
you could do:
<input type="text" formControlName="name" disabled="{{!showName}}">
As soon as I did that, I was able to dynamically disable / enable elements in my forms.
I hope this helps!
This should work
toggleName() : void { let ctrl = this.form.get('name') ctrl.enabled ? ctrl.disable() : ctrl.enable() }
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