Both mat-error show when only one error appeared.
I\'m trying to make custom validators with mat-error. Both input for email and confirm password are red when each
Creating a customErrorMatcher
Well, if we want to show an error in a <mat-form-field>
when the input
is valid, we use a customErrorMatcher.
This is a class like
class CrossFieldErrorMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
//when we want to show the error
return true
//when we want not show the error
return false
}
}
Normally we has in our component
errorMatcher=new CrossFieldErrorMatcher()
//and the .html
<mat-form-field>
<input matInput formControlName='verifyPassword'
[errorStateMatcher]="errorMatcher">
<mat-error *ngIf="....">
Passwords do not match!
</mat-error>
</mat-form-field>
Well, we are change the things a bit, adding a constructor in our customErrorMatcher
class CrossFieldErrorMatcher implements ErrorStateMatcher {
constructor(private name:string){} //<--add a constructor
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
//when we want to show the error, but we can use "name"
return true
//when we want not show the error
return false
}
}
Then, our component becomes
errorMatcher(name:string)
{
return new CrossFieldErrorMatcher(name);
}
//and the .html
<mat-form-field>
<input matInput formControlName='verifyPassword'
[errorStateMatcher]="errorMatcher('password')">
<mat-error *ngIf="....">
Passwords do not match!
</mat-error>
</mat-form-field>
The email address field shows an error because the error state matcher checks the parent - which is the form - which is in error because the password fields do not match. You need to use different error state matchers for the email field and password fields because the conditions are different - email does not need to be in error if the password fields don't match.