[英]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.