【问题标题】:Angular 4 + Angular Material 2 Template Form field validation not workingAngular 4 + Angular Material 2 模板表单字段验证不起作用
【发布时间】:2017-09-13 21:08:57
【问题描述】:

我有一个搜索字段,其中显示带有动态内容的下拉菜单。我希望能够显示模式验证错误。代码如下:

<md-input-container class="search-container">
  <input mdInput
         validateField
         [(ngModel)]="currentSearchResult"
         [disabled]="tdDisabled"
         (keyup)="performSearch(currentSearchResult)"
         [mdAutocomplete]="searchAuto" placeholder="{{'COMPANY.SEARCH' | translate}}">
  <md-error *ngIf="currentSearchResult.touched && currentSearchResult.invalid">
    <span *ngIf="currentSearchResult.errors.pattern">
      Invalid characters used.
    </span>
  </md-error>
</md-input-container>

我得到这个错误:

TypeError: Cannot read property 'touched' of undefined
    at Object.eval [as updateDirectives] (SearchComponent.html:8)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13058)
    at checkAndUpdateView (core.es5.js:12238)
    at callViewAction (core.es5.js:12603)
    at execComponentViewsAction (core.es5.js:12535)
    at checkAndUpdateView (core.es5.js:12244)
    at callViewAction (core.es5.js:12603)
    at execComponentViewsAction (core.es5.js:12535)
    at checkAndUpdateView (core.es5.js:12244)
    at callViewAction (core.es5.js:12603)

哪个指向这条线:

<md-error *ngIf="currentSearchResult.touched && currentSearchResult.invalid">

我不太明白为什么没有定义它们的变量。我尝试使用 ngModel name="currentSearchResult"#currentSearchResult="ngModel" 但这也给出了错误。

我在这个字段中缺少什么? 谢谢

【问题讨论】:

  • 你能提供你的.ts文件吗?

标签: angular angular-material2 angular-validation


【解决方案1】:

试试这个语法(为了清楚起见,我删除了一些部分)

<md-input-container class="search-container">
  <input mdInput
         [(ngModel)]="currentSearchResult"
         required
         name="myModel" 
        #myModel="ngModel">


  <md-error *ngIf="myModel.touched && myModel.invalid">
    <span *ngIf="myModel.errors.required">
      Invalid characters used.
    </span>
  </md-error>
</md-input-container>

DEMO

【讨论】:

  • @Swoox 你可以有许多类型的错误,如必需、模式等。所以&lt;span&gt;errors.required 可以指定这些错误类型。
猜你喜欢
  • 1970-01-01
  • 2018-12-30
  • 2016-12-30
  • 2020-11-03
  • 2016-10-30
  • 2017-11-25
  • 2018-04-28
  • 2018-05-12
  • 2018-03-09
相关资源
最近更新 更多