mrsan22
mrsan22

Reputation: 747

Using custom validators on md-error with mdAutocomplete and md-input-container. (Material 2)

I am trying to use md-error tag to display error messages on an mdAutocomplete. I am using Angular with Material 2 components. The md-error message is displayed for built-in validators like required. However, I also want to display another error message with md-error when No Matching Records are found (basically when user types something which is not there in the dropdown). So, I tried having another md-error with an *ngIf but this error message is never shown. I googled about it and looks like the solution is to have a custom validation method or Directive. Material 2 provides a way to have custom validation method but I am not able to use it with my template based form. Could anyone provide me an example of using custom validation on a template based form using md-error?

Sample Code:

This didn't work:

<md-input-container>
  <input mdInput
         placeholder="Currency Type"
         [(ngModel)]="policyObj.cost.premium.currencyType.name"
         [mdAutocomplete]="premiumCurrencyTypeAuto"
         [disabled]="disable"
         (keydown)="PanelOptions($event, policyObj.cost.premium.currencyType, filteredPremiumCurrencyType, premiumCurrencyTypeAuto)"
         (ngModelChange)="filteredPremiumCurrencyType = filterCurrency(policyObj.cost.premium.currencyType.name)"
         name="currency_type1" required>
     <md-error>This field is required</md-error>
     <md-error *ngIf="filteredPremiumCurrencyType?.length === 0"> No Matching
        Records Found!</md-error>
</md-input-container>

<md-autocomplete #premiumCurrencyTypeAuto="mdAutocomplete" [displayWith]="displayFn">
  <md-option *ngFor="let ct of filteredPremiumCurrencyType" [value]="ct">
    {{ ct.name }}
  </md-option>
</md-autocomplete>

I tried looking at Material 2 - Custom Error Matcher but was not sure on how to use it in my case with template based forms. Any help would be appreciated. Thanks!

Upvotes: 1

Views: 972

Answers (1)

Will Howell
Will Howell

Reputation: 3715

errorStateMatcher should work just the same with template and reactive forms. Something like this should work for your use case:

<md-input-container>
  <input mdInput [errorStateMatcher]="myErrorStateMatcher.bind(this)" ... >
  <md-error *ngIf="policyObj.cost.premium.currencyType.name === ''">This field is required</md-error>
  <md-error *ngIf="filteredPremiumCurrencyType?.length === 0" No Matching Records Found!</md-error>
</md-input-container>


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

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

Upvotes: 2

Related Questions