Angular Material showing two error messages
You can have one <mat-error>
check if the control is invalid
and then get your appropriate error message i.e.:
<mat-error *ngIf="form.controls['username'].invalid">{{ getErrorMessage() }}</mat-error>
And then in your .ts
you would have a function to retrieve the appropriate error message:
getErrorMessage() {
return this.form.controls['username'].hasError('required') ? 'You must enter a value' :
this.form.controls['username'].hasError('pattern') ? 'Not a valid username' :
this.form.controls['username'].hasError('minlength') ? 'Required length is at least 3 characters' :
'';
}
You don't need those divs
, the <mat-error>
element should suffice if you have appropriate styles applied.
Here is a stackblitz example.
Was having the same problem.
This is what I came up with, simple and elegant.
No simultaneous mat-error
's will be shown when there are two or more.
Yet, the whole form will be invalid, disabling the submission.
mat-error + mat-error {
display: none;
}