Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HostListener

Tags:

angular

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?

like image 695
uksz Avatar asked Apr 01 '16 06:04

uksz


People also ask

What is the use of @HostListener?

@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.

What is the use of HostListener in Angular?

HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

Can I use HostListener in service?

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.

What is the HostBinding decorator doing in this directive?

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.


1 Answers

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) } 
like image 74
Günter Zöchbauer Avatar answered Sep 28 '22 18:09

Günter Zöchbauer