I have a component called ListComponent and I have the following code in it.
@HostListener("document:keydown", ["$event"])
handleKeyEvent(event: KeyboardEvent) {
switch(event.keyCode) {
case 38: //up arrow
this.selectPreviousItem();
break;
case 40: //down arrow
this.selectNextItem();
break;
}
}
When I press up arrow or down arrow key, event fires for all instances of the component on a page. How can I fire the event only for the focused element?
I think it's better to create a directive and call it in the element to focus.
@Directive({
selector: 'focusItem',
})
export class MyDirective {
constructor() { }
@HostListener('focus', ['$event.target'])
onFocus(target) {
console.log("Focus called 1");
}
}
call it in the element
<input focusItem>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With