Key event filtering for numbers, letters or other groups

偶尔善良 提交于 2019-12-13 07:26:27

问题


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.


回答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]'
})
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();
        }
      }
  }
}


来源:https://stackoverflow.com/questions/45116152/key-event-filtering-for-numbers-letters-or-other-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!