Why mat-error not get displayed inside mat-form field in angular material 6 withcustom global validators

有些话、适合烂在心里 提交于 2019-12-05 03:58:55

Yes, mat-error does not show up by default. It only shows when the input is touched.

But, luckily you can override this behavior using errorStateMatcher input property, bound to mat-input element.

The pull request in which this feature was added.

Usage :

<mat-form-field>
    <input matInput [errorStateMatcher]="matcher" [matDatepicker]="picker" placeholder="Choose a Start date" 
    formControlName="FromDate"
      [min]="minFromDate" 
           [max]="maxToDate" >
    <mat-datepicker-toggle matSuffix [for]="picker" ></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
    <mat-error >Please provide a valid Fromdate</mat-error> 
  </mat-form-field> 

So you have to implement ErrorStateMatcher in your code this way.

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

And in your component add a new object matcher for ErrorStateMatcher class, which will act as a value to [errorStateMatcher]="matcher"

matcher = new MyErrorStateMatcher();

I have also added the same code in your forked stackblitz

Suggestion :

You need not provide a ngIf condition for mat-error specifying your formControlName. It will be automatically considered based on the mat-form-field in which it is present.

I Found a very simple solution without overriding the ErrorStateMatcher Class, simply you could import in the app.module.ts

import { ErrorStateMatcher, ShowOnDirtyErrorStateMatcher } from '@angular/material'; 
  @NgModule({  providers: [AlertService, { provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher }],})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!