pantonis
pantonis

Reputation: 6467

Angular 5 validation error not shown on input change

I have a problem with an input control where if I type 501 (not valid value) the mat-error is not shown unless input loses focus. How can I show it when the user types in an invalid value without input losing focus? This is the html

<div class="col-auto form margin-top-17 margin-left-10" [formGroup]="activationPointsFormGroup">
            <mat-form-field style="width:230px!important">
                <input matInput type="number" placeholder="Range" [formControl]="activationPointsFormControl" 
                (keydown.enter)="loadData()">
                <mat-error class="margin-top-1" *ngIf="activationPointsFormControl.errors">
                    Valid values are between -500 and 500 and not 0
                </mat-error>
            </mat-form-field>
 </div>

and the typescript code

  public activationPointsFormGroup: FormGroup;
  public activationPointsFormControl: FormControl;

  private createForm(): void {
        this.activationPointsFormControl = new FormControl(1, [Validators.required, Validators.min(-500), Validators.max(500)]);
        this.activationPointsFormGroup = new FormGroup({
            timeThresholdFormControl: this.activationPointsFormControl,
        });

        this.activationPointsFormControl.valueChanges.subscribe(value => {

            if (value) {
                this.selectedActivationPoints = value;
            }
        });
    }

Upvotes: 2

Views: 3553

Answers (1)

AVJT82
AVJT82

Reputation: 73357

For this, you need an error state matcher, to customize the angular material validation behavior, import ErrorStateMatcher and...

import {ErrorStateMatcher} from '@angular/material/core';

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && control.dirty);
  }
}

This will now show the error message when control is dirty. Declare a an error state matcher in your component...

matcher = new MyErrorStateMatcher();

and then mark it on your input field:

<input matInput [errorStateMatcher]="matcher" ...>

Here's a demo, which will show that email is not valid while user is typing...

StackBlitz

Upvotes: 4

Related Questions