我试图使用md-error
标记在mdAutocomplete上显示错误消息。我使用的角度与材料2组件。md-error
消息为内置验证器(如required
)显示。但是,我还想在md-error
中显示另一条No Matching Records are found
错误消息(基本上是当用户键入下拉列表中没有的内容时)。因此,我尝试使用另一个带有md-error
的*ngIf
,但是这个错误消息从未显示过。我在谷歌上搜索过,看起来解决方案是有一个定制的验证方法或指令。Matter2提供了一种具有自定义验证方法的方法,但我无法在我的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>
我试着查看材料2-自定义误差匹配器,但不确定如何在基于模板的表单中使用它。任何帮助都将不胜感激。谢谢!
发布于 2017-08-01 14:22:33
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)));
}
https://stackoverflow.com/questions/45447613
复制