One challenge I am facing is how to determine the caps lock state when initializing a directive. The current setup only detects changes after a key press, but what if the user enters the page with caps lock already activated? Here is the existing code for the directive (credit to Vega's answer):
import { Directive, EventEmitter, HostListener, OnInit, Output } from '@angular/core';
@Directive({
selector: '[capsLock]',
})
export class CapslockDirective implements OnInit{
@Output('capsLock') capsLock: EventEmitter<boolean> = new EventEmitter<boolean>();
capsOn!: boolean;
ngOnInit(): void {
// detect caps lock state here
}
@HostListener('window:keydown', ['$event'])
onKeyDown(event: KeyboardEvent): void {
this.capsOn = event.getModifierState && event.getModifierState('CapsLock');
this.capsLock.emit(this.capsOn);
}
@HostListener('window:keyup', ['$event'])
onKeyUp(event: KeyboardEvent): void {
this.capsOn = event.getModifierState && event.getModifierState('CapsLock');
this.capsLock.emit(this.capsOn);
}
}
Can Angular handle detecting caps lock in its initial state?