Angular2:用 ngIf 指令包装时 ngModel 不工作

Angular2: ngModel not working when wrapped with an ngIf directive

我在尝试通过模板引用变量引用 NgModel 指令时看到 "Cannot read property 'valid' of undefined" 错误 -- 但只有当它被包装在 *ngIf.

中时才会出现

这是一个展示问题的示例表单:

<form (ngSubmit)="true">
  <div [ngClass]="dom_email_ok.valid ? 'one' : 'two'">
    <span><input [(ngModel)]="email" #dom_email_ok="ngModel" required name="email" /></span>
  </div>
  <div [ngClass]="dom_email_bad.valid ? 'one' : 'two'">
    <span *ngIf="true"><input [(ngModel)]="email" #dom_email_bad="ngModel" required name="email" /></span>
  </div>
</form>

这是 Plunker:http://plnkr.co/edit/3xrqCVv7qE1FQjdTdzXP

这对第一个 input 很好用。当它尝试根据包裹在 *ngIf 中的 input 设置 class 时发生错误:

TypeError: Cannot read property 'valid' of undefined
    at CompiledTemplate.proxyViewClass.View_App0.detectChangesInternal (/AppModule/App/component.ngfactory.js:259:51)
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (https://unpkg.com/@angular/core/bundles/core.umd.js:12726:18)

具体来说,生成的代码对于有效的代码如下所示:

var currVal_8_0_0 = (self._NgModel_11_7.context.valid? 'one': 'two');

...对于不起作用的那个看起来像这样:

var currVal_14_0_0 = (self.context.dom_email_bad.valid? 'one': 'two');

这个函数中,self.context是组件本身,所以没有dom_email属性(只有nameemail)。

您不能在 *ngIf 之外使用在 *ngIf 内部声明的变量。

但是你可以使用这个:

<div>
  <h2>Hello {{name}}</h2>
  <form (ngSubmit)="true">
    <div [ngClass]="dom_email_ok.valid ? 'one' : 'two'">
      <span><input [(ngModel)]="email" #dom_email_ok="ngModel" required name="email" /></span>
    </div>
    <div [ngClass]="dom_email_bad.valid ? 'one' : 'two'" *ngIf="true">
      <span ><input [(ngModel)]="email" #dom_email_bad="ngModel" required name="email" /></span>
    </div>
  </form>
</div>