0
votes

I created a Custom Validator method that checks if a value typed into a mat-autocomplete exists in an Array.

This method returns { isExchange: true }. I use this.tradeForm.get( 'exchange' ).hasError( 'isExchange' ) inside another method that returns an error message. This all works fine.

Part of the mat-autocomplete, inside the mat-form-field tags, I added the following code:

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

Somehow this doesn't show up when there is an error, however, when I change the mat-error tags to small tags, it works.

I have read that a mat-error only shows up when a FormControl is invalid, but I can't find out why mine isn't.

Has anyone got an idea what I am missing out?

Maybe some value I need to change in the control to have the mat-error tags show up?

Here's what the validator function looks like:

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

And this is how it's used:

    this.tradeForm = new FormGroup({
        exchange: new FormControl( this.newTrade.Exchange.Title, [this.isExchange] );
    });
1
remove the *ngIf="tradeForm.get( 'exchange' ).invalid", the mat-error component does that for you. If your mat-error is inside a matFormField which contains an input bound to "exchange" control it should work out of the box.Pierre Mallet

1 Answers

1
votes

I have found a working solution by adding control.markAsTouched() inside my validator function.