Angular 2 Two way binding with [disabled]

14,339

Solution 1

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

Solution 2

In your question, both option values are 0.

You'll want to ensure that one is true, with the other being false


Component:

component class {
    myVar = false
}

Template:

<select [(ngModel)]="myVar">
    <option value="true">...</option
    <option value="false">...</option
</select>

<select [disabled]="myVar">
    <option>...</option
</select>

Solution 3

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>
Share:
14,339
Vishnu Sureshkumar
Author by

Vishnu Sureshkumar

Software Engineer

Updated on June 20, 2022

Comments

  • Vishnu Sureshkumar
    Vishnu Sureshkumar almost 2 years

    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>