Angular HostListener multiple instances of the same component

I have a component called ListComponent, and I have the following code.

  @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 click the arrow or the down arrow, the event fires for all instances of the component on the page. How can I fire an event only for a focused element?

+4
source share
1 answer

I think it’s better to create a directive and call it in an element to focus.

@Directive({
    selector: 'focusItem', 
    })

  export class MyDirective {
    constructor() { }
    @HostListener('focus', ['$event.target'])
      onFocus(target) {
        console.log("Focus called 1");
      }
  }

call it in an element

<input focusItem>  
+1
source

Source: https://habr.com/ru/post/1691416/


All Articles