我有一个名为 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>
关于javascript - Angular HostListener 同一组件的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47993873/