Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Two way binding with [disabled]

I have an input with [disabled] depending upon the ngModel of another input. Initially [disabled] is working properly but not when we change the dependant input value, the [disabled] property is not working. How to apply two binding on [disabled] property?

Following is the code snippet.

<select [ngModel]="isDisabled" (ngModelChange)="isDisabled=$event">
<option value="0">Disabled</option>
<option value="0">Enabled</option>
</select>

This model isDisabled is changed correctly. I could see the value change like this in template {{isDisabled}}. But not reflected in the [disabled] property of the select box.

<select [ngModel]="userInput" [disabled]="isDisabled">
<option value="test">Test</option>
</select>
like image 881
Vishnu Sureshkumar Avatar asked Oct 17 '22 11:10

Vishnu Sureshkumar


2 Answers

The primary problem was you were using same value 0 for both option. But even if you change them to 1 & 0 respectively for Enable & Disable. It will not gonna work because value attribute stores values as '0'(string '0') & '1'(string 1) (in short stringify value of it).

You could easily solve this dataType issue of value by using ngValue attribute binding.

<select [ngModel]="isDisabled" (ngModelChange)="isDisabled=$event">
  <option [ngValue]="1">Disabled</option>
  <option [ngValue]="0">Enabled</option>
</select>

Plunker Demo

like image 147
Pankaj Parkar Avatar answered Oct 20 '22 11:10

Pankaj Parkar


you need to add a name attribute to the input and make the ng-mode two-way binding by wrapping up with parenthesis also. no need to use the ngModelChange for this purpose

<select [(ngModel)]="isDisabled"  name='isDisabled'>
        <option value="0">Disabled</option>
        <option value="1">Enabled</option>
</select>
<select [(ngModel)]="userInput" [disabled]="isDisabled == '0'" name='userInput'>
        <option value="test">Test</option>
</select>
like image 32
Sachila Ranawaka Avatar answered Oct 20 '22 11:10

Sachila Ranawaka