I am wondering how can I use @HostListener
. The only info I've found, was in the cheatsheet :
@HostListener('click', ['$event']) onClick(e) {...}
I am trying to log the element that user has clicked on. I've tried like that:
@HostListener('click')({
onClick(e) {
console.log(e)
}
})
But then I receive an error of:
TypeError: decorator is not a function(…)
Any ideas?
@HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.
HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.
Seems like its not possible to use HostListener in a service. like Stanislasdrg Reinstate Monica wrote, there's a more elegant and more angular way using the renderer.. You could use the old way window.
HostBindinglink Decorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.
The error message is quite accurate. A decorator is just for decorating a function (or a class, field, parameter, ...) Just put it before the code you want to decorate:
@HostListener('click', ['$event']) onClick(e) { console.log(e) }
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