【发布时间】:2018-07-29 13:30:58
【问题描述】:
我创建了一个自定义验证器方法,用于检查输入到 mat-autocomplete 的值是否存在于数组中。
此方法返回 { isExchange: true }。我在另一个返回错误消息的方法中使用 this.tradeForm.get('exchange').hasError('isExchange')。这一切都很好。
mat-autocomplete的一部分,在mat-form-field标签里面,我添加了如下代码:
<mat-error *ngIf="tradeForm.get( 'exchange' ).invalid">{{getFormErrorMessage( 'exchange' )}}</mat-error>
不知何故,当出现错误时,这不会显示出来,但是,当我将 mat-error 标签更改为 small 标签时,它可以工作。
我已经读到只有当 FormControl 无效时才会出现 mat-error,但我不知道为什么我的不是。
有人知道我错过了什么吗?
也许我需要在控件中更改一些值才能显示 mat-error 标签?
验证器函数如下所示:
isExchange( control: FormControl ) {
let exchanges = [{ID: 1, Title: 'BitTrex'}, {ID: 2, Title: 'Bitfinex'}, {ID: 3, Title: 'Binance'}, {ID: 4, Title: 'Kraken'}, {ID: 5, Title: 'Coinmarketcap'}];
if( exchanges.find( exchange => exchange.Title === control.value ) === undefined ) {
control.markAsTouched(); // This makes it work, not sure why
return { isExchange: true };
} else {
return null;
}
}
这就是它的使用方式:
this.tradeForm = new FormGroup({
exchange: new FormControl( this.newTrade.Exchange.Title, [this.isExchange] );
});
【问题讨论】:
-
删除 *ngIf="tradeForm.get( 'exchange' ).invalid",mat-error 组件会为您执行此操作。如果您的 mat-error 位于 matFormField 中,其中包含绑定到“交换”控件的输入,它应该可以开箱即用。
标签: angular angular-material2 angular4-forms angular-validation mat-autocomplete