Angular 4 + Angular Material 2 Template Form field validation not working

1.4k Views Asked by At

I have a search field which displays drop down with dynamic content. I want to be able to show a pattern validation error. Here is the code:

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

I get this error:

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)

Which points to this line:

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

I don't quite understand why they variable is not defined. I tried using the ngModel name="currentSearchResult" and #currentSearchResult="ngModel" but that gave also errors.

What am I missing with this field? Thanks

1

There are 1 best solutions below

1
On BEST ANSWER

Try this syntax (I removed some parts for the clarity)

<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