【发布时间】:2017-06-06 10:43:55
【问题描述】:
我在尝试通过模板引用变量引用 NgModel 指令时看到“无法读取未定义的属性‘有效’”错误 - 但仅当它包含在 *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 设置类时会发生错误:
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属性(只有name和email)。
【问题讨论】:
标签: angular angular2-forms angular2-directives