7

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?

1 Answer 1

2

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>  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.