Ram
Ram

Reputation: 563

Angular2/4 material-design, <mat-error> not working - when no results found

I am using Angular4 Material Design with WebAPI - I am trying to get to display a validation message - "No matches found" when a user enter an invalid value in the (Material Auto Complete).

I have tried few things based on google searches:- https://material.angular.io/components/input/overview#custom-error-matcher https://github.com/angular/material2/blob/4383f51a58de1fccad2ed64443a5e22ab435c02b/src/demo-app/input/input-demo.ts#L56

and below is my current implementation:-

HTML

     <div class="form-group spaces" style="width: 30%">
     <mat-form-field>
     <input  [errorStateMatcher]="myErrorStateMatcher.bind(this)" matInput 
     placeholder="NUMBER" [matAutocomplete]="auto" type="text" 
     formControlName="validNumber" required [formControl]="stateCtrl">
     <md-error *ngIf="validNumbers?.length === 0"> No Matching Records 
     Found!
     </md-error>
    </mat-form-field>

    <mat-autocomplete #auto="matAutocomplete" mat-no-cache="true">
    <mat-option *ngFor="let c of validNumbers " [value]="c">{{c}}</mat-
    option>
    </mat-autocomplete>
    </div>

Typescript:-

 import { ErrorStateMatcher } from '@angular/material/core';
 public validNumbers;

 myErrorStateMatcher(control, form): boolean
 {
    if (this.validNumbers && !this.validNumbers.length)
    {
        return true;
    }

    // Error when invalid control is touched, or submitted
    const isSubmitted = form && form.submitted;
    return !!(control.invalid && (control.touched || isSubmitted));
  }

Error message attached:- Error Message

Upvotes: 3

Views: 1926

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

myErrorStateMatcher needs to be a class instance, not a function. Also, .bind(this) isn't necessary / doesn't do anything since you this is not accessible in the template.

See docs: https://material.angular.io/components/input/overview#custom-error-matcher

You should be able to just create an object with isErrorState:

@Component(...)
class MyComponent {
  ...
  myErrorStateMatcher = {
    isErrorState(control, form) {
      /* do your check here */
    }
  }

If that doesn't work you can also try myErrorStateMatcher: ErrorStateMatcher =. Ultimately you may need to / want to create a class:

class MyErrorStateMatcher implements ErrorStateMatcher

that has the isErrorStateMethod you're using and then set myErrorStateMatcher = new MyErrorStateMatcher in your component.

Upvotes: 2

Related Questions