I am currently working on a form that includes an email field. Upon saving the form, the onRegisterFormSubmit function is called. Within this function, I handle errors returned by the API - specifically setting errors in the email form control and retrieving error messages. In the HTML, I have logic to display error messages when the control has an error, but unfortunately, the message does not appear in case of an error.
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
matcher = new MyErrorStateMatcher();
this.registerForm = this.formBuilder.group({
'email': ['', Validators.compose([Validators.required, emailValidator])]
});
public onRegisterFormSubmit(): void {
if (this.registerForm.valid) {
this.facade.register(); // save the form
this.ngrxFormsFacade.errors$.subscribe(error => { // get errors from api
if (error & error.email) {
this.registerForm.controls.email.setErrors({ 'emailExist': true });
this.errorEmailMsg = error.email;
}
})
}
}
<mat-form-field appearance="outline" class="w-100 mt-1">
<mat-label>Email</mat-label>
<input matInput placeholder="Email" formControlName="email" [errorStateMatcher]="matcher" required>
<mat-error *ngIf="registerForm.controls.email.hasError('emailExist')">{{errorEmailMsg}}</mat-error>
<mat-error *ngIf="registerForm.controls.email.errors?.required">Email is required</mat-error>
<mat-error *ngIf="registerForm.controls.email.hasError('invalidEmail')">Invalid email address</mat-error>
</mat-form-field>