DEV Community

Anirban Mukherjee
Anirban Mukherjee

Posted on • Updated on

Handle CAPS-LOCK on/off event in Angular

This is an interesting, yet quite commonly expected, use-case - warn the user that the CAPS-LOCK is ON, specially while entering a password, so that the user is aware of it and can change it, if needed.

GitHub logo anirbmuk / ng-capslock-demo

Angular 13.3.0 application to demonstrate how to display CAPS-LOCK-ON/OFF message

Preview

There are a few scenarios handled in this demonstration:

  1. Change the message when the user toggles the caps-lock while on the password field.
  2. Also change the message when the user changes the caps-lock state elsewhere (maybe in another application or browser tab, etc) and then comes back to this application.
  3. Remove the events when component is destroyed, to prevent memory leaks.
  4. Run change-detection when ChangeDetectionStrategy is OnPush.

Let's see about 1 & 2.

By the way, I am on @angular/cli 13.3.0 and @angular/material 13.3.6. For the message, I have used mat-hint on mat-form-field.

To achieve this, we grab the reference of the password field (using @ViewChild) and then add a couple of event handlers to the underlying HTMLInputElement - keyup and mousedown.

The keyup event handler will toggle the message when the user toggles the CAPS-LOCK button while being on the password field. This generates a KeyboardEvent.

The mousedown event handler will toggle the message when the user changes the state elsewhere and the navigates back to the application and clicks on the password field. This will be beneficial for the user since the information is now provided even before something is typed. This is done through a MouseEvent.

ngAfterViewInit


Some improvements:

To prevent memory leaks, we need to remove these event handlers once the component is destroyed.
ngOnDestroy

If the ChangeDetectionStrategy is set to OnPush, we need to mark the component for a change detection whenever either of the above events are fired. So, at the end of the event handler, use

this.cdRef.markForCheck();
Enter fullscreen mode Exit fullscreen mode

The browser's password manager may auto-fill the password data for you. This will also fire a keyup event, but this will not be an instance of KeyboardEvent and will thus not have the getModifierState method. So we will ignore this!

if (event?.type === 'keyup' && !(event instanceof KeyboardEvent)) {
  return;
}
Enter fullscreen mode Exit fullscreen mode

Cheers!
Anirban Mukherjee

Top comments (1)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Nice one! good post :)