An empty variable gives a true value to the disabled attribute on the input
I don't know if this is a problem or normal behavior.
If we have a form like this:
<form #form="ngForm" >
<div>
<label>field1</label>
<input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar" />
</div>
<div>
<label>field2</label>
<input type="text" name="field2" [(ngModel)]="someVar" />
</div>
</form>
At the same time the variables mainVar and someVar are set to an empty string in the component:
mainVar = '';
someVar = '';
This will disable the input named field1 even though someVar is an empty string. As far as I know, a variable that is an empty string should return false for an if statement.
But the weirdest thing is that if I remove the [(ngModel)] attribute from the input field1 it works as it should (enter field1 strong> will be disabled if I type something in the field2 tab )
source to share
UPDATE
I found the answer to this question in the angular source code (<3 open source!). The controller ngModel
explicitly checks ''
on change disabled input
. If the input is strictly equal ''
, the element will be disabled. So it's by design.
This is what the source code looks like ( GitHub link , see lines 142 and 217)
const isDisabled = disabledValue === '' || (disabledValue && disabledValue !== 'false');
This means that you cannot use an empty string as false to set the input that is using ngModel
to disable it.
This is how you get around it
<input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar ? true : false" />
source to share