首页 文章

mat-error不会出现错误

提问于
浏览
0

我创建了一个Custom Validator方法,用于检查在数组中是否存在类型为mat-autocomplete的值 .

此方法返回{isExchange:true} . 我在另一个返回错误消息的方法中使用this.tradeForm.get('exchange') . hasError('isExchange') . 一切正常 .

mat-aut-completed的一部分,在mat-form-field标签内,我添加了以下代码:

<mat-error *ngIf="tradeForm.get( 'exchange' ).invalid">{{getFormErrorMessage( 'exchange' )}}</mat-error>

不知何故,当出现错误时,这不会显示,但是,当我将mat-error标签更改为小标签时,它可以正常工作 .

我已经读过,只有当FormControl无效时才会显示mat-error,但我无法找出为什么我的不是 .

Has anyone got an idea what I am missing out?

也许我需要在控件中更改一些值才能显示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] );
    });

1 回答

  • 1

    我通过在验证器函数中添加control.markAsTouched()找到了一个有效的解决方案 .

相关问题