Rohan Sampat
Rohan Sampat

Reputation: 970

Component specific HostListener in angular 2

I'm developing an app in Angular 2 in which I have a parent component and child component. The child component has a HostListener of keydown event and executes some functionality. I'm able to achieve this, but the problem is if I press any key in context of the parent component then HostListener also executes. What I want is HostListener to execute if I'm in context of the child component.

This is not working as I intend to. It is in child Component

@HostListener('keydown', ["$event"])
ondropdown(){ functionality }

This is working but on the whole page, I even tried 'window' but the effect is same.

@HostListener('document:keydown', ["$event"])
ondropdown(){ //functionality }

Upvotes: 2

Views: 5981

Answers (1)

Vega
Vega

Reputation: 28738

It seems to me that you have a bubbling. In this case you should stop the event bubbling from the child component to the parent and prevent the default event from the parent to child .

For the child:

  @HostListener('keydown', ["$event"])
    ...
      event.stopPropagation();
    }

For the parent:

  @HostListener('keydown', ["$event"])
    ...
      event.preventDefault();
    }

Upvotes: 3

Related Questions