I would like to get the caps lock state when initializing a directive. Currently the directive detects changes after pressing the key, but what about the situation when the user enters the page with caps lock already active? Currently, the directive code looks like this (thanks 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);
}
}
Is it even possible in pure Angular?