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

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)="...">
  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...