通过 mdAutocomplete 和 md-input-container 在 md-error 上使用自定义验证器。 (Material 2)

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

我正在尝试使用 md-error 标记在 mdAutocomplete 上显示错误消息。我正在使用 Angular 和 Material 2 个组件。 md-error 消息会针对 required 等内置验证器显示。但是,我还想在 No Matching Records are found 时显示另一条带有 md-error 的错误消息(基本上当用户键入下拉列表中不存在的内容时)。因此,我尝试使用另一个 md-error*ngIf,但从未显示此错误消息。我在谷歌上搜索了一下,看起来解决方案是使用自定义验证方法或指令。 Material 2 提供了一种自定义验证方法的方法,但我无法将其与我的 template based form 一起使用。谁能给我提供一个使用 md-error 在基于模板的表单上使用自定义验证的示例?

示例代码:

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>

我尝试查看 Material 2 - Custom Error Matcher 但不确定如何在基于模板的表单中使用它。任何帮助,将不胜感激。谢谢!

errorStateMatcher 应该与模板和响应式表单一样工作。这样的事情应该适用于您的用例:

<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)));
}