防止Angular Web组件侦听影子DOM之外的keydown事件

问题描述

我在页面上嵌入了一个Web组件。我有一个特定的快捷方式设置,可以监听某些按键。但是,当我在Web组件之外单击时,它仍会触发Web组件的侦听器。

这是我的意思的示例:

@HostListener("document:keydown",["$event"])
handleKeyboardEvent(event: KeyboardEvent) {
    const key = event.key.toUpperCase();

    if(key === "SPACE") {
        alert("Pressing space is not allowed");
    }
}

这是我的HTML可能的样子:

<body>
    <h1>Welcome to the front page</h1>
    <input type="text" placeholder="Search..." />

    <p>Sign up to our newsletter:</p>
    <newsletter-signup></newsletter-signup> <!-- enter email,click button,etc. inside the component -->
</body>

当我按组件内的 space 时,它会发出警告,提示不允许。很好。

但是,当我在页面的搜索输入中按 space 时,它也会触发。即使在重新加载页面后仅单击space / kbd>,它仍然会触发它。

如何防止这种情况在组件外部发生?注意,HostListener应该侦听整个组件上的按键事件。这意味着我不能简单地将侦听器限制为特定的输入元素。

我的组件正在使用影子DOM:

@Component({
    ...,encapsulation: ViewEncapsulation.ShadowDom
})

解决方法

将听众置于% set RE {(?:^|[^-+])\yhello\y(?:$|[^-+])} (?:^|[^-+])\yhello\y(?:$|[^-+]) % regexp $RE "hello" 1 % regexp $RE "ahello" 0 % regexp $RE "+hello" 0 % regexp $RE "+ hello" 1 % regexp $RE "hello+" 0 % regexp $RE "hello-" 0 % regexp $RE "hello.-" 1 上,就不能防止触发事件。

在事件处理程序内部,您可以检查事件的来源并忽略

使用:

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...