Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger keydown event only for alphanumeric and special characters in Angular7?

I have a keydown event and I want it to be triggered when I press alphanumeric or special characters like #$@.

  <input type="text" style="width: 70%;" [(ngModel)]= "textMessage" (keydown) ="sendTypingEvent()" >

I want to restrict the event NOT to be triggered at all for keys such as enter, escape (esc), shift, alt, tab, backspace and command (meta), arrows and f keys (f1 though f12).

Is there a way to set up a REGEX pattern at the HTML?

<input (keydown.a)="..."> --expect to trigger

I can have the event triggered and filter the key at the function call as shown below. However, trying to see if there are any other options.

sendTypingEvent(event) {
  if (event.key === "Enter" || event.key ==='esc' .... ) {
    console.log("skip this event");
  }

}
like image 446
javapedia.net Avatar asked Oct 15 '22 07:10

javapedia.net


1 Answers

Here are two ways to restrict keydown event -

  1. you allow the alphanumeric key press only
sendTypingEvent(event){
        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90)){
            console.log("input was 0-9");
            console.log("input was a-z");
            return true;
        }

        return false;
    }
  1. You can restrict specific keys
sendTypingEvent(event){
        if ((event.keyCode >= 112 && event.keyCode <= 123) || event.keyCode == 16){
            console.log("Disabled f11 to f12, shift keys");
            return false
        }
}

Get Keycode for this website -

https://keycode.info/

like image 75
Nikhilesh Agrawal Avatar answered Nov 01 '22 14:11

Nikhilesh Agrawal