javascriptangulartypescriptcapslock

Detect and warn users about caps lock is on


How to implement to detecting and warning users when caps lock is on with (or not) tooltip style in typescript (angular 4.2.2)?? Maybe with some keyup events, or like toUpperCase() in JS.


Solution

  • Write a directive and add a listener. Add it to your component's main wrapper div, so component would get the emits. As soon it receives the event change, trigger the state of a property linked to a label tag. It will help to hide and show with *ngIf, the condition being the response from your listener (via an @Output to the component).

    The following displays a message dynamically:

    HTML:

    <div (capsLock)="capsOn=$event">
      <input type="text"  >
      <label *ngIf="capsOn">Caps Locked</label>
    </div>
    

    Directive:

    @Directive({ selector: '[capsLock]' })
    export class TrackCapsDirective {
      @Output('capsLock') capsLock = new EventEmitter<Boolean>();
    
      @HostListener('window:keydown', ['$event'])
      onKeyDown(event: KeyboardEvent): void {
        const capsOn = event.getModifierState && event.getModifierState('CapsLock');
          this.capsLock.emit(capsOn);
      }
      @HostListener('window:keyup', ['$event'])
      onKeyUp(event: KeyboardEvent): void {
        const capsOn = event.getModifierState && event.getModifierState('CapsLock');
          this.capsLock.emit(capsOn);
      }
    }
    

    DEMO