我正在尝试使用md-error
标记在mdAutocomplete上显示错误消息。我正在使用Angular和Material 2组件。对于md-error
等内置验证程序,会显示required
消息。但是,我还希望在md-error
时显示另一条带有No Matching Records are found
的错误消息(基本上当用户键入下拉菜单中没有的内容时)。因此,我尝试使用另一个md-error
和*ngIf
,但此错误消息从未显示过。我用Google搜索,看起来解决方案是使用自定义验证方法或指令。材料2提供了一种自定义验证方法,但我无法将其与template based form
一起使用。任何人都可以使用md-error
?
示例代码:
这没有用:
<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,但不确定如何在我的情况下使用基于模板的表单。任何帮助,将不胜感激。谢谢!
答案 0 :(得分:2)
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)));
}