【发布时间】:2018-10-13 23:40:02
【问题描述】:
我有一个密码更改表格,只要新密码和重复密码不相等,“保存密码”按钮就会被禁用。
为了保持控制器“干净”,我将Template Element Reference 映射到重复input。
<form>
<input [(ngModel)]="newPassword"
type="password"
name="new-password"
id="new-password">
<input type="password"
name="new-password-repeat"
id="new-password-repeat"
#passwordRepeatInput>
<!-- This is the output -->
<pre>{{passwordRepeatInput.value}}</pre>
<button [disabled]="!!newPassword && passwordRepeatInput.value"
class="btn btn-primary">
Save password
</button>
现在意想不到的事情发生了。当我更改重复字段的值时,输出不会改变。但是,一旦我在表单中更改了另一个输入,输出就变成了输入元素的值——所以它并不代表分配了 [(ngModel)] 属性的元素。
一旦我在我的控制器中指定了一个新的模型属性并通过[(ngModel)] 将其映射到重复字段,模板元素引用就会起作用,并在输入值更改时更改输出。
<input type="password"
name="new-password-repeat"
id="new-password-repeat"
[(ngModel)]="passwordRepeatModelVal" // This solves the problem
#passwordRepeatInput>
但是有没有办法在控制器中没有不必要的属性的情况下建立预期的行为?
【问题讨论】:
-
我不明白。调用绑定到
newPasswordRepeat或passwordRepeatModelVal的组件属性有什么区别?在第一种情况下,newPasswordRepeat是什么? -
对于
passwordRepeatModelVal,我必须在控制器中删除一个属性,但使用模板引用#passwordRepeatInput应该不需要此声明 -
但在您的第一种情况下,
newPasswordRepeat不是模板引用,是吗?它引用了什么? -
如果
newPasswordRepeat没有定义,那么passwordRepeatInput.value总是相同的(可能是一个空字符串)。 -
# char 是的,他的模型分配在这里太多了
标签: angular typescript variables angular-ngmodel angular-forms