首页 > 代码库 > [Angular] HostListener Method Arguments - Blocking Default Keyboard Behavior

[Angular] HostListener Method Arguments - Blocking Default Keyboard Behavior

We are going to see how to using method arguments for @HostListener.

 

 

First, we can use HostListener without method arguments:

    @HostListener(dblclick)    toggle(){        this.collapsed = !this.collapsed;    }

It works fine. 

 

But if we need to get the $event object and do something with it, for example using preventDefault() from the event object. Then we need to use method arguments:

  @HostListener(keydown, [$event, $event.keyCode])  onKeyDown($event: KeyboardEvent, keyCode) {if(keyCode !== TAB) {      $event.preventDefault();    }  }

Here we inject ‘$event‘ and ‘$event.keyCode‘ into the method arguments. So for onKeyDown() method, we are able to inject those as well.

 

[Angular] HostListener Method Arguments - Blocking Default Keyboard Behavior