reika
reika

Reputation: 526

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?

Upvotes: 7

Views: 2658

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

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>  

Upvotes: 2

Related Questions