空变量为输入的禁用属性提供真实值 [英] Empty variable gives true value to disabled attribute on input

查看:91
本文介绍了空变量为输入的禁用属性提供真实值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是问题还是正常行为.

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>

同时,在组件中将变量 mainVar someVar 设置为空字符串:

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

mainVar = '';
someVar = '';

这将导致名称为 field1 的输入被禁用,即使 someVar 是空字符串.据我所知,为空字符串的变量应将 false 返回给if语句.

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.

但是最奇怪的是,如果我从输入 field1 中删除 [(ngModel)] 属性,它将按预期工作(输入 field1 field2 )

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)

柱塞示例

推荐答案

更新

我在有角度的源代码中找到了答案(<3个开源!).更改 disabled 时, ngModel 控制器显式检查''.如果输入严格等于'',则该元素将被禁用.因此,这种行为是设计使然.

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.

这是源代码的外观(链接到GitHub ,请参阅第142和217行)

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

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

这意味着您不能使用空字符串作为伪造来设置使用 ngModel 禁用它的输入.

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

这是您的解决方法

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

> 工作的监听器示例

这篇关于空变量为输入的禁用属性提供真实值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆