【问题标题】:Angular2: ngModel not working when wrapped with an ngIf directiveAngular2:使用 ngIf 指令包装时,ngModel 不起作用
【发布时间】: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属性(只有nameemail)。

【问题讨论】:

    标签: angular angular2-forms angular2-directives


    【解决方案1】:

    您不能在 *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>
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2016-07-14
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多