Angular's HostListener
decorator takes two arguments. The first specifies the name of event to listen for. The second is an optional array of strings unilluminatingly named args
. Naturally, its meaning isn't currently explained in the docs (which currently devote an entire four words to documenting the HostListener
decorator, the first two of which state that it is, uh, the "HostListener decorator").
I've only ever seen HostListener
called in two ways:
args
argument entirely (e.g. at https://angular.io/guide/styleguide#style-06-01)args
argument as ['$event']
, e.g. at https://angular-2-training-book.rangle.io/handout/advanced-angular/directives/listening_to_an_element_host.html
What does this mysterious args
parameter do, and why is it sometimes specified as ['$event']
?
The HostBinding & HostListener are decorators in Angular. HostListener listens to host events, while HostBinding allows us to bind to a property of the host element. The host is an element on which we attach our component or directive.
As described before, this directive will turn any element that it is placed on into its host element and it set its mouseenter event listener on the host element through @HostListener . As you can see in the code, you would declare the @HostListener decorator method with the DOM event passed in as the argument, followed by its event handler method.
Having many directives that listen to the same event on the global elements could eventually hurt the performance of your application. Lastly, just like in Angular event binding, you can also use Angular Pseudo-Events with @HostListener.
What is @hostListener in Angular? 1 It is a decorator which specifies the DOM Event to be captured 2 Specifies event handler which needs to be invoked on the event call 3 @hostListener receives Event Name and Callback Function associated 4 @hostListner can capture event info triggered by user More ...
$event
is the reserved name for the actual event value like it can be used in (click)="clickHandler($event)"
event bindings.
@HostListener('eventName', args)
supports an array of values like
['$event.target.value', '$event.name']
that specifies what values will be passed as parameters to the event handler.
It looks like just always passing $event
(assuming ['$event']
as default) would be a more reasonable approach,
but if WebWorker is used, this way the amount of data passed between UI thread and WebWorker thread can reduced by only passing that part(s) of the event that are actually required by the event handler (or no value at all if the parameter is omitted).
See also https://angular.io/api/core/HostListener#args
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With