Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


How to detect if key is pressed in Angular
On an Angular Typescript page, you may want to know if a certain key is being pressed (outside of the normal key events on an input field).
To determine this, use HostListener and track the key(s) you are interested in.
Here is an example with the boolean "shiftPressed" flag tracking whether the Shift key is currently pressed:

import { Component, HostListener, Inject } from '@angular/core';


shiftPressed = false;

@HostListener('document:keydown', ['$event'])
handleKeyDown(event: KeyboardEvent) {
if (event.shiftKey) {
this.shiftPressed = true;
@HostListener('document:keyup', ['$event'])
handleKeyUp(event: KeyboardEvent) {
if (!event.shiftKey) {
this.shiftPressed = false;

Created By: amos 11/3/2023 1:44:04 PM
Updated: 11/3/2023 1:44:43 PM