Angular HostListener function only activates once the page is focused

I'm encountering an issue with a component that has a button. I've implemented a simple HostListener to display a notification when the ALT + Q shortcut is triggered.

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

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

The problem is that the notification only appears after clicking on the component. Any ideas on what might be causing this and how to fix it?

Thank you!

Answer №1

It is important to understand why the application should trigger the shortcut, as failing to do so may lead to a focus being triggered after the view has been initialized.

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);

Check out the Stackblitz Demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 7 makes it a breeze to move elements using the drag and

Is there a way to drag and drop elements from an expansion panel while still keeping them displayed within the panel after being dropped? I am looking for Angular 7 code to achieve this functionality. Your assistance is much appreciated. I attempted to dr ...

Resolve the conflict with the upstream dependency when setting up a fresh Angular project

Software Info: Angular CLI: 12.1.1 Node: 14.17.3 Package Manager: npm 7.19.1 An error occurred while attempting to create a new Angular project. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While re ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Create typings for object properties in TypeScript

I am inexperienced with TypeScript and am looking to set up types for my object keys. I have explored a few methods to accomplish this, but I am encountering an issue where an error is not triggered when assigning a value of a different type. For example: ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...

Angular - Binding not displaying the latest list elements

In my small application, I have two buttons that either add 1 or -1 to a list. The sum of the list is also displayed. However, I am facing an issue with the interpolation as only the default values of the list are being displayed instead of the newly adde ...

Encountered an issue: Unable to access the property 'querySelectorAll' of null and Unable to access the property 'getElementsByTagName' of null

*<div class="col-md-12" *ngIf="data_client2.length>0"> <button class="btn print" printSectionId="listVotantesPrint" ngxPrint i18n="@@downloadList"></button> ' <button class=&qu ...

Is the scrolling functionality acting strange while using React Three Fiber?

In my React Three Fiber application, I have the following structure: Website Canvas NativeHTMLContent Canvas Website The issue I'm facing is that after scrolling down the entire canvas, the scrollbar resets to the top and starts scrolling from the t ...

Concealed URL - Navigation with Angular 2 Routing

Is it possible to conceal the URL when using window.open()? Alternatively, can the Angular2 router be utilized to open the URL in a fresh tab? I am familiar with the method of concealing the URL during routing by using this.router.navigate(["/Pages"], { s ...

Detecting changes in Angular when the @Input() value remains the same

I have created an Angular Custom scroll directive that utilizes an @Input() to pass an HTML element as a parameter, allowing the scrollbar to move to that specific element. However, I've encountered an issue where if I pass the same HTML Element mult ...

Resolving ES6 type conflicts while compiling TypeScript to Node.js

I seem to be facing some challenges with the TypeScript 2 type system when working with Node.js. Let me explain the situation: I am compiling a small Node.js Express server written in TypeScript to plain ES5 for running under Node 6.10.0 (target: ES5 in ...

finishing an observation after a sequence of responses

In my current scenario, I am dealing with an observable that sequentially calls promises within it. My goal is to have the observable complete only after all promises in a forEach loop have been successfully processed. However, I am facing an issue where ...

Encountering Error: Cannot find Property xxx on type xxx during Angular 6 Build

My project has an unusual issue where it builds and runs perfectly, but when attempting to build it on the SYS server, I encounter the following error: ERROR in (html) Property 'ExampleDate' does not exist on type 'ExampleComponent'. ( ...

Develop a personalized React route component using TypeScript. The error message "Property 'path' does not exist on type... RouteProps" is displayed

I am currently working on creating my own route component using React. Although I am new to TypeScript, I believe that is the root cause of the issue I am facing. import * as React from 'react' import { ApplicationState } from '../../store& ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

Having issues with *ngFor in Angular when trying to retrieve data from an API

I have been working on fetching data from an API and displaying it on the frontend, but I am facing an issue with *ngFor. Even though all variables seem to be set up correctly and I can see the data in the console.log, it is not showing up on the frontend. ...

What is the proper way to integrate "require" into my Angular 2 project?

Currently, I am still in the process of trying to integrate the angular 2 code mirror module into my angular 2 application. Previously, I faced some challenges with imports which I discussed in detail here, and managed to overcome them. However, a new iss ...

unfamiliar element detected in custom component

I recently created a simple component in Ionic as a test. I used the Ionic CLI to generate the component, and here is an excerpt from my app.module.ts file: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/p ...

Error message when running `ng serve` - tips for troubleshooting?

I recently retrieved an older angular project (about 6 months old) that I wanted to use as a template. However, when I attempt to run it, I encounter the errors mentioned below. After doing some research online and reading through a few links, I found sugg ...

What is the correct way to nest multiple ng-if statements?

I'm currently grappling with a problem involving multiple nested ngIf directives applied to ng-template elements in Angular.js, and I've yet to find the ideal solution. While I am aware of workarounds, they are not as efficient as I would like th ...