NgxMatErrors provides an easy, yet flexible solution for displaying error messages in a MatFormField.
See it in action on StackBlitz
Install ngx-mat-errors
in your project:
npm install ngx-mat-errors
Import the NgxMatErrorsModule
in your app.module.ts
:
import {
NgxMatErrorsModule
} from 'ngx-mat-errors';
@NgModule({
imports: [
...
NgxMatErrorsModule
],
})
export class AppModule {}
Add ngx-mat-errors
to your mat-error
in your mat-form-field
.
<mat-form-field>
<mat-label>Label</mat-label>
<input type="text" matInput [formControl]="control">
<mat-error ngx-mat-errors></mat-error>
</mat-form-field>
ngx-mat-errors
can be used as an @Input()
to override the MatFormFieldControl
.
<mat-form-field>
<mat-label>Label</mat-label>
<input type="text" matInput #input="matInput" [formControl]="control1" autocomplete="off">
</mat-form-field>
<mat-error [ngx-mat-errors]="input"></mat-error>
There are 2 ways to customize your error messages.
There is the NGX_MAT_ERROR_DEFAULT_OPTIONS
injection token, you can provide it in your app.module.ts
with useClass
, or useFactory
and customize your error messages globally.
This example changes only the min
error message.
export const NGX_MAT_ERROR_DEFAULT_CONFIG: Provider = {
useFactory: () => {
return {
...DEFAULT_ERROR_MESSAGES,
min: (error: MinError) =>
`Min value is ${error.min}, actual is ${error.actual}`,
};
},
provide: NGX_MAT_ERROR_DEFAULT_OPTIONS,
};
@NgModule({
...
providers: [NGX_MAT_ERROR_DEFAULT_CONFIG],
})
export class AppModule {}
You can customize your error messages even more with *ngxMatErrorDef
directive.
<mat-form-field>
<mat-label>Label</mat-label>
<input type="text" matInput [formControl]="control1">
<mat-error ngx-mat-errors>
<span *ngxMatErrorDef="let error; for: 'pattern'">
Only digits are allowed, up to 12 digits.
</span>
<ng-container *ngxMatErrorDef="let error; for: 'min'">
The minimum value is {{error.min}}.
</ng-container>
</mat-error>
</mat-form-field>
@angular/core
:^14.0.0
,@angular/material
:^14.0.0
,
<mat-form-field>
<mat-label>Label</mat-label>
<input type="text" matInput [formControl]="control">
<mat-error ngx-mat-errors></mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Label</mat-label>
<input type="text" matInput [(ngModel)]="value">
<mat-error ngx-mat-errors></mat-error>
</mat-form-field>
Run npm run develop
to build the library and generate an NPM package.
The build artifacts will be stored in the dist/ngx-mat-errors
folder.
Run npm start
for a dev server. Navigate to http://localhost:4202/
. The app will automatically reload if you change any of the source files.