javascriptangularkeyboard-eventseventfilter

Key event filtering for numbers, letters or other groups


Angular4 docs shows ( Key event filtering (with key.enter) ) how to catch keyboard keystrokes events easier - (keyup.enter)="foo()" or keyup.w or keyup.space etc.

What I need is to fire event only if letters being pressed.

One way I can think of is:

<input id="textFilter" (keyup)=“foo($event)”>

  foo(e){
    var allowedKeys = [‘KeyQ’, ‘KeyW’, ‘KeyE’, and the rest of the alphabet...]
    if (allowedKeys.indexOf(e.code) != -1 ) {
      return true;
    }
  }

But I would expect such pseudo-events already build-in in Angular. For ex. for letters, like - (keyup.letters)="foo()" and for numbers, like -(keyup.numbers)="foo()". Are there any? And is that solution above is preferable for filtering keyboard keystrokes by groups?

docs

I appreciate any help.


Solution

  • AFAIK there are no keyup groups provided by angular. But you can easily create custom directive to allow/disallow your own set of keys.

    Here's a demo of allowing letters only.

    only-letters.directive.ts:

    import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    
    @Directive({
      selector: '[onlyLetters]'
    })
    export class OnlyLetters {
    
      constructor(private el: ElementRef) { }
    
      @Input() onlyLetters: boolean;
    
      @HostListener('keydown', ['$event']) onKeyDown(event) {
        let e = <KeyboardEvent> event;
        if (this.onlyLetters) {
          
          // console.log(e);
          
          if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
              // let it happen, don't do anything
              return;
            }
            // Ensure that it is a number and stop the keypress
            if (((e.keyCode < 65 || e.keyCode > 90)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
          }
      }
    }