如何解决防止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
上,就不能防止触发事件。
在事件处理程序内部,您可以检查事件的来源并忽略。
使用:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。