Angular HostListener 在关注页面之前不起作用

问题描述 投票:0回答:1

我有一个组件,其中有一个按钮

有一个简单的 HostListener,它将在快捷方式(ALT + Q)上显示通知

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

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

仅当我单击组件时一切才开始工作,在此之前通知不会出现

原因是什么以及适当的解决方案?

谢谢!

angular typescript
1个回答
1
投票

就是这样,因为不关注应用程序为什么要触发快捷方式,你可以在视图初始化后触发焦点,希望它有帮助!

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 演示

© www.soinside.com 2019 - 2024. All rights reserved.