Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HostListener multiple instances of same component

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?

like image 949
reika Avatar asked Dec 27 '17 14:12

reika


1 Answers

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>  
like image 175
Sachila Ranawaka Avatar answered Nov 14 '22 23:11

Sachila Ranawaka