【问题标题】:Angular2+ Input element with Template Element Reference not updating带有模板元素参考的Angular2 +输入元素未更新
【发布时间】: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>

但是有没有办法在控制器中没有不必要的属性的情况下建立预期的行为?

【问题讨论】:

  • 我不明白。调用绑定到newPasswordRepeatpasswordRepeatModelVal 的组件属性有什么区别?在第一种情况下,newPasswordRepeat 是什么?
  • 对于passwordRepeatModelVal,我必须在控制器中删除一个属性,但使用模板引用#passwordRepeatInput 应该不需要此声明
  • 但在您的第一种情况下,newPasswordRepeat 不是模板引用,是吗?它引用了什么?
  • 如果newPasswordRepeat 没有定义,那么passwordRepeatInput.value 总是相同的(可能是一个空字符串)。
  • # char 是的,他的模型分配在这里太多了

标签: angular typescript variables angular-ngmodel angular-forms


【解决方案1】:

如果您将ngModel 指令本身应用于重复input 元素,视图也应该正确更新,而不将其绑定到属性:

<input type="password"
       name="new-password-repeat"
       id="new-password-repeat"
       ngModel
       #passwordRepeatInput>

this stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2013-05-12
    • 2017-06-11
    • 2015-05-12
    • 2017-12-13
    相关资源
    最近更新 更多