I'm currently working on an authentication application utilizing the PEAN stack - PostgreSQL, ExpressJS, Angular, and NodeJS.
Within my project, I've implemented an autofocus directive:
autofocus.directive.ts
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[autofocusDirective]',
})
export class AutofocusDirective {
constructor(private host: ElementRef) {}
ngAfterViewInit() {
this.host.nativeElement.focus();
}
}
This directive functions as intended for the most part.
Issue
However, a problem arises when navigating to a different route after clicking a button. For example, upon clicking the Sign up button, while transitioning to the Sign up component, there is a brief moment where the error message appears in the Sign in component. This behavior is expected but undesirable. Refer to the provided GIF below.
https://i.sstatic.net/lemVF.gif
Inquiry
How can I prevent form error messages triggered by the autofocus directive from being displayed when switching to another component?
The handling of form error messages is done like this:
sign-in.component.ts
/* ... */
// Establish a form group for sign in
formSignIn = new FormGroup({
signInEmail: new FormControl('', [Validators.required]), // An email input that must be filled
signInPassword: new FormControl('', [Validators.required]), // A password input that must be filled
});
// Retrieve error message for email field
getErrorMessageEmail() {
// Display 'Email is required' if no email is entered
return this.formSignIn.controls['signInEmail'].hasError('required') ? 'Email is required' : '';
}
// Retrieve error message for password field
getErrorMessagePassword() {
// Display 'Password is required' if no password is entered
return this.formSignIn.controls['signInPassword'].hasError('required') ? 'Password is required' : '';
}
/* ... */