Add Keyboard Shortcuts to Your Angular App
Angular provides a special syntax for registering keyboard events. A keyboard event can be bound to a specific key
or code
. It’s assumed by default that you’ll use the key
field on the keyboard event.
Combinations of keys can be used by separating them with a period
. For example, keydown.enter
allows binding events to the enter
key. We can also use modifier keys, such as shift
, alt
, control
, and meta
.
This website is great for exploring different event values:
Three APIs can use this syntax — template event binding, HostListener
, and Renderer2.listen()
:
To use the code
field, we need to add the code
keyword after the event name:
Note that it also works with a lowercase value instead of KeyK
.
If you need to use the period
key, it doesn’t work using the key
syntax. You can use the code
syntax in this case:
Read about the differences between using the key
and the code
value here and decide which is best for your use case:
Here are some other examples:
Follow me on Medium or Twitter to read more about Angular and JS!