Empty variable gives true value to disabled attribute on input

China☆狼群 提交于 2021-01-27 13:21:36

问题


I dont 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>

In the same time variables mainVar and someVar are set to empty string in the component:

mainVar = '';
someVar = '';

This will result in input with name field1 being disabled, even though someVar is empty string. To my knowledge, variable that is empty string, should return false to if statement.

But the strangest thing is that if i remove [(ngModel)] attribute from input field1, it will work as it should (input field1 will be disabled if I type something into input field2)

Plunker example


回答1:


UPDATE

I found the answer to this in the angular source code (<3 open source!). The ngModel controller explicitly checks for '' when the disabled input is changed. If the input strictly equals '', the element will be disabled. So this behavior is by design.

Here is how to source code looks (link to GitHub, see line 142 and 217)

const isDisabled = disabledValue === '' || (disabledValue && disabledValue !== 'false');

This means that you cannot use an empty string as falsy to set an input that is using ngModel to disable it.

Here is how you get around it

<input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar ? true : false"  />

Working plunker example




回答2:


Set it to null/undefined/false, and it will not be disabled. String empty is still a value.



来源:https://stackoverflow.com/questions/43231752/empty-variable-gives-true-value-to-disabled-attribute-on-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!