#var="ngModel" 的含义

Meaning of #var="ngModel"

我正在创建 login.component.html,在此期间我创建了一个输入字段,然后将其绑定到 login.component.ts 中的 email 变量。最初我把它写成:

<input type="text" placeholder="Enter Email" id="email"
       [(ngModel)] = "email" name = "email" required #email="ngModel"/>

但继续收到错误,直到我将其更改为:

<input type="text" placeholder="Enter Email" id="email"
       [(ngModel)] = "email" name = "email" required #em="ngModel"/>

#em="ngModel" 到底发生了什么,为什么我只能使用非常具体的值?

您提到的语法在 the form validation docs 中提到,他们在其中解释:

The template variable (#name) has the value "ngModel" (always ngModel). This gives you a reference to the Angular NgModel directive associated with this control that you can use in the template to check for control states such as valid and dirty.

问题是您的 @Component class 上有一个名为 email 的 属性 和它的 email 上有一个名为 emailreference variable模板。你不能同时拥有两者,因此你会看到错误:

Error: Cannot assign to a reference or variable!

重命名 属性 或参考变量(在您的情况下,您将后者更改为 em)可解决问题。您不限于 "incredibly specific values",您可以更改为任何不是 属性.

的有效标识符

几天前我遇到了同样的问题,当我对其进行研发时我发现

 #var="ngModel" exports NgModel into a local variable called "var".

通过这个我们可以检查控制状态例如有效感动