1

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.

Screenshot

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' : '';
}

/* ... */
Rok Benko
  • 14,265
  • 2
  • 24
  • 49

1 Answers1

0

It looks mostly like you are in a catch-22. If you focus on the input, it is no longer considered pristine and when you click something else, removing the focus, you are triggering the error for Validators.required.

Maybe instead change the validator to Validators.email (so that you are still validating the input) and in the login method called, if an email is not provided then manually assign the error formSignIn.controls['signInEmail'].setErrors({'required': true}). On successful login, you can remove the error or just ignore it since the component should be destroyed anyway.

  • 1
    Thanks for the response. Hm, this is not an option because the sign-in method is called on the *Sign in* button click, which is disabled until the whole form is valid. I need to display an error saying that the email is required before the user is able to click the button. Any other ideas? – Rok Benko Aug 18 '23 at 09:46
  • If possible, could you throw your code on a stackblitz and post the link in your question? Then I could directly poke around the code and figure out a solution. – Myles Morrone Aug 19 '23 at 18:12