This content originally appeared on DEV Community and was authored by Anirban Mukherjee
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.
anirbmuk / ng-capslock-demo
Angular 13.3.0 application to demonstrate how to display CAPS-LOCK-ON/OFF message
There are a few scenarios handled in this demonstration:
- Change the message when the user toggles the caps-lock while on the password field.
- 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.
- Remove the events when component is destroyed, to prevent memory leaks.
- Run change-detection when
ChangeDetectionStrategy
isOnPush
.
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
onmat-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
.
Some improvements:
To prevent memory leaks, we need to remove these event handlers once the component is destroyed.
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();
Cheers!
Follow me on Twitter or connect with me on LinkedIn
This content originally appeared on DEV Community and was authored by Anirban Mukherjee
Anirban Mukherjee | Sciencx (2022-05-07T20:58:06+00:00) Handle CAPS-LOCK on/off event in Angular. Retrieved from https://www.scien.cx/2022/05/07/handle-caps-lock-on-off-event-in-angular/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.