1

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

<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"and#currentSearchResult="ngModel"但这也给出了错误。

我在这个领域缺少什么?谢谢

4

1 回答 1

3

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

<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>

演示

于 2017-09-13T13:08:57.650 回答