[英]Angular HostListener multiple instances of same component
我有一个名为ListComponent的组件,我有以下代码。
@HostListener("document:keydown", ["$event"])
handleKeyEvent(event: KeyboardEvent) {
switch(event.keyCode) {
case 38: //up arrow
this.selectPreviousItem();
break;
case 40: //down arrow
this.selectNextItem();
break;
}
}
当我按向上箭头键或向下箭头键时,事件将触发页面上组件的所有实例。 如何仅针对焦点元素触发事件?
我认为最好创建一个指令并在要关注的元素中调用它。
@Directive({
selector: 'focusItem',
})
export class MyDirective {
constructor() { }
@HostListener('focus', ['$event.target'])
onFocus(target) {
console.log("Focus called 1");
}
}
在元素中调用它
<input focusItem>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.