空变量为输入的禁用属性提供真值 [英] Empty variable gives true value to disabled attribute on input
问题描述
我不知道这是问题还是正常行为.
如果我们有这样的表格:
<div><label>field2</label><input type="text" name="field2" [(ngModel)]="someVar"/>
</表单>
同时在组件中将变量mainVar和someVar设置为空字符串:
mainVar = '';someVar = '';
这将导致名称为 field1 的输入被禁用,即使 someVar 是空字符串.据我所知,为空字符串的变量应该将 false 返回给 if 语句.
但最奇怪的是,如果我从输入 field1 中删除 [(ngModel)] 属性,它会正常工作(输入 field1如果我在输入中输入内容 field2)
,strong> 将被禁用UPDATE
我在 angular 源代码中找到了答案(<3 开源!).ngModel
控制器在 disabled input
更改时明确检查 ''
.如果输入严格等于 ''
,则元素将被禁用.所以这种行为是设计使然.
以下是源代码外观的方法(链接到 GitHub,见第 142 和 217 行)
const isDisabled = disabledValue === '' ||(disabledValue && disabledValue !== 'false');
这意味着您不能使用空字符串作为虚假来设置使用 ngModel
禁用它的输入.
这就是你解决它的方法
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)
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" />
这篇关于空变量为输入的禁用属性提供真值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!