Search code examples
angulartypescript

Angular HostListener does not work before focusing on page


I have a component, where we have a button

There is a simple HostListener, which will display a notification on shortcut (ALT + Q)

  @HostListener('window:keydown.alt.q', ['$event'])
  displayNotification(event: KeyboardEvent) {
    event.preventDefault();

    this.messageService.add({
      severity: 'success',
      detail: 'Finished',
      life: 5
    });
   }

Everything starts working only if I perform a click on the component, before that the notification does not appear

What is the cause and the appropriate solution?

Thanks!


Solution

  • That is how it is, because without focusing on the application why should the shortcut trigger, you could trigger a focus after the view is initialized, hope it helps!

    import { Component, HostListener } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <h1>Hello from {{ name }}!</h1>
        <a target="_blank" href="https://angular.dev/overview">
          Learn more about Angular
        </a>
      `,
    })
    export class App {
      name = 'Angular';
    
      @HostListener('window:keydown.alt.q', ['$event'])
      displayNotification(event: KeyboardEvent) {
        event.preventDefault();
        alert('shortcut!');
      }
    
      ngAfterViewInit() {
        window.focus();
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo