Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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]'
})
exportclassOnlyLetters {

  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 anythingreturn;
        }
        // Ensure that it is a number and stop the keypressif (((e.keyCode < 65 || e.keyCode > 90)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
      }
  }
}

Post a Comment for "Key Event Filtering For Numbers, Letters Or Other Groups"