Back to Tips

Keycodes

Angular's CDK provides a module with commonly used keycode constants. These are useful for handling keyboard events in your components.

import { Directive } from "@angular/core";
import { UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW } from "@angular/cdk/keycodes"; // KEYCODES!

@Directive({
  selector: "[count-arrows]",
  standalone: true,
  host: {
    "(keydown)": "handleKeyPress($event)",
  },
})
export class ArrowCounterDirective {
  arrowPressCount = 0;

  handleKeyPress(event: KeyboardEvent) {
    if ([UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW].includes(event.keyCode)) {
      this.arrowPressCount++;
    }
  }
}

Support

If you enjoyed this tip and found it useful, consider buying me a coffee. Thanks in advance!

Buy Me a Coffee at ko-fi.com
Using Angular v.19.0.3 🚀