@HostListener keydown event not firing on whole app

I want to capture keydown events for my entire app (specifically to navigate with arrow keys)

This works fine on any sub components, but things at the menu or root or header level don’t work. So the user has to click into the component, then press a key.

I want to capture keypresses from my entire app

Adding the below to my main app.component does not fire at all

  @HostListener('keydown', ['$event'])
  handleKeyboardEventkeydown(event: KeyboardEvent) { 
    console.log('keydown AppComponent:', event.key) // never logs
  }

The same code in my home.component (where router points to), and in my sub-component that actually manages the inner page. Only on that last one does the event fire, but never in app or home components

My app component html is


<ion-app>
  <ion-menu contentId="main-content" type="overlay">
    <ion-header>
      <ion-toolbar>
        <ion-title>Menu</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>

      <ion-list>
        <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages">
          <ion-item [routerDirection]="'root'" [routerLink]="[p.url]">
            <ion-icon slot="start" [name]="p.icon"></ion-icon>
            <ion-label> {{ p.title }} </ion-label>
          </ion-item>
        </ion-menu-toggle>
      </ion-list>
    </ion-content>


  </ion-menu>
  <ion-router-outlet id="main-content"></ion-router-outlet>
</ion-app>

How can I get my HostListener on the app.component to capture keypresses. Or how/where else might I accomplish this?

Update

changing to @HostListener(‘window:keydown’, …) fixed my issue!

1 Like