I'm building an authentication app using the PEAN stack (i.e., PostgreSQL - ExpressJS - Angular - NodeJS).
I have a directive for autofocus as follows:
autofocus.directive.ts
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[autofocusDirective]',
})
export class AutofocusDirective {
constructor(private host: ElementRef) {}
ngAfterViewInit() {
this.host.nativeElement.focus();
}
}
It does the job perfectly in general.
Problem
However, if I click a button that navigates to another route, then I get an annoying glitch. In the example below, I clicked on the Sign up button, which takes the user to the Sign up component. In the exact moment I clicked on the button, the error message appeared for a split second on the Sign in component. I understand that the behavior described is expected. See the GIF below.
Question
How not to show form error messages using the autofocus directive when routing to a different component?
I handle form error messages as follows:
sign-in.component.ts
/* ... */
// Create a form group for sign in
formSignIn = new FormGroup({
signInEmail: new FormControl('', [Validators.required]), // Email is a required field
signInPassword: new FormControl('', [Validators.required]), // Password is a required field
});
// Get error message for email field
getErrorMessageEmail() {
// If the email is not entered
return this.formSignIn.controls['signInEmail'].hasError('required') ? 'Email is required' : '';
}
// Get error message for password field
getErrorMessagePassword() {
// If the password is not entered
return this.formSignIn.controls['signInPassword'].hasError('required') ? 'Password is required' : '';
}
/* ... */