Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading