Tutorial

Angular Quick Tip: Binding Specific Keys to the Keyup and Keydown Events

Angular

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

When binding to either the keyup or keydown events in your Angular 2+ templates, you can specify key names. This makes it very easy to trigger the event only when specific keys are pressed.

First, let’s see an example without using a key name. Let’s say we want the event to be triggered only when the user presses the enter key:

<input (keydown)="onKeydown($event)">
onKeydown(event) {
  if (event.key === "Enter") {
    console.log(event);
  }
}

Now the same example, but made simpler with the addition of the enter key name to the event:

<input (keydown.enter)="onKeydown($event)">
onKeydown(event) {
  console.log(event);
}

Key Combinations

You can also combine keys together to trigger the event only when the key combination is triggered. In the following example, the event will trigger only if the control and 1 keys are pressed at the same time:

<input (keyup.control.1)="onKeydown($event)">

Some Examples

This feature works for special and modifier keys like enter, escape (esc), shift, alt, tab, backspace and command (meta), but it also works for letters, numbers, arrows and f keys (f1 though f12).

Here are quite a few more examples, to give you an idea of what’s possible:

<input (keydown.enter)="...">
<input (keydown.a)="...">
<input (keydown.esc)="...">
<input (keydown.shift.esc)="...">
<input (keydown.control)="...">
<input (keydown.alt)="...">
<input (keydown.meta)="...">
<input (keydown.9)="...">
<input (keydown.tab)="...">
<input (keydown.backspace)="...">
<input (keydown.arrowup)="...">
<input (keydown.shift.arrowdown)="...">
<input (keydown.shift.control.z)="...">
<input (keydown.f4)="...">
Creative Commons License