Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Disable input change not working

Tags:

forms

angular

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.

like image 813
Glenn Utter Avatar asked Sep 15 '16 06:09

Glenn Utter


People also ask

How to disable the input in Angular?

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 .


2 Answers

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!

like image 57
Vidal Quevedo Avatar answered Sep 30 '22 22:09

Vidal Quevedo


This should work

toggleName() : void {    let ctrl = this.form.get('name')   ctrl.enabled ? ctrl.disable() : ctrl.enable() } 
like image 42
Günter Zöchbauer Avatar answered Oct 01 '22 00:10

Günter Zöchbauer