6

Given the example at https://material.angular.io/components/form-field/overview

<div class="example-container">
  <mat-form-field>
    <input matInput placeholder="Enter your email" [formControl]="email" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>


import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

/** @title Form field with error messages */
@Component({
  selector: 'form-field-error-example',
  templateUrl: 'form-field-error-example.html',
  styleUrls: ['form-field-error-example.css']
})
export class FormFieldErrorExample {
  email = new FormControl('', [Validators.required, Validators.email]);

  getErrorMessage() {
    return this.email.hasError('required') ? 'You must enter a value' :
        this.email.hasError('email') ? 'Not a valid email' :
            '';
  }
}

The error seems to be triggered on-blur. Only after leaving the input does the error appears. It is the same in my application. In this current mode, error exist but the is not displayed until the input loses focus.

How can I trigger the error to be displayed when the input change.

2 Answers 2

14

As per the docs you need to use an errorStateMatcher.

For you that would look like this:

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

and in your component do:

matcher = new MyErrorStateMatcher();

Then just add in your input field

[errorStateMatcher]="matcher"

StackBlitz

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please also explain what is the purpose of [formControl]="email" in the StackBlitz? There is no formControl property exposed by the component and also FormControl doesn't seem to be a directive. So I'm confused here.
this did not solve the problem. the required error still gets triggered on blur
2

and in your component class:

matcher = {
  isErrorState: () => {
    return this.statusField; // return Boolean status value
  }
};

Then just add in your matInput field

[errorStateMatcher]="matcher"

2 Comments

This answer also works for simple inputs using ngModel
What is statusField? It doesn't exists

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.