我有一个组件,其中有一个按钮
有一个简单的 HostListener,它将在快捷方式(ALT + Q)上显示通知
@HostListener('window:keydown.alt.q', ['$event'])
displayNotification(event: KeyboardEvent) {
event.preventDefault();
this.messageService.add({
severity: 'success',
detail: 'Finished',
life: 5
});
}
仅当我单击组件时一切才开始工作,在此之前通知不会出现
原因是什么以及适当的解决方案?
谢谢!
就是这样,因为不关注应用程序为什么要触发快捷方式,你可以在视图初始化后触发焦点,希望它有帮助!
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);