Angular 4 + Angular Material 2模板表单字段验证不起作用

时间:2017-09-13 12:52:40

标签: angular angular-material2 angular-validation

我有一个搜索字段,显示带有动态内容的下拉列表。我希望能够显示模式验证错误。这是代码:

<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",但这也给出了错误。

我对这个领域缺少什么? 感谢

1 个答案:

答案 0 :(得分:2)

尝试这种语法(为清晰起见,我删除了一些部分)

<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