Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2, HostListener, how can I target an element? can I target based on class?

In Angular2, how can I target an element within the HostListener decorator?

@HostListener('dragstart', ['$event'])     onDragStart(ev:Event) {         console.log(ev);     }  @HostListener('document: dragstart', ['$event'])     onDragStart(ev:Event) {         console.log(ev);     }  @HostListener('myElement: dragstart', ['$event'])     onDragStart(ev:Event) {         console.log(ev);     }  @HostListener('myElement.myClass: dragstart', ['$event'])     onDragStart(ev:Event) {         console.log(ev);     } 

The two first work. Any other thing I've tried raises an EXCEPTION: Unsupported event target undefined for event dragstart

So, can I implement it to a targeted element? How?

like image 801
GWorking Avatar asked Jan 17 '17 15:01

GWorking


People also ask

Can we use HostListener in component?

@HostListener is Angular's decorator method that's used for listening to DOM events on the host element of both component and attribute directives.

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.

What is HostBinding in angular?

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


2 Answers

@HostListener() only supports window, document, and body as global event targets, otherwise it only supports the components host element.

like image 130
Günter Zöchbauer Avatar answered Sep 19 '22 13:09

Günter Zöchbauer


Since the accepted answer doesn't actually help to solve the problem, here is a solution.

A better way to achieve this is by creating a directive, this way you can add the directive to any element you wish, and the listeners will only trigger for this particular element.

For example:

@Directive({    selector: "[focus-out-directive]" }) export class FocusOutDirective {    @Output() onFocusOut: EventEmitter<boolean> = new EventEmitter<false>();     @HostListener("focusout", ["$event"])    public onListenerTriggered(event: any): void {        this.onFocusOut.emit(true);    } } 

Then on your HTML elements you wish to apply this listener to, just add the directive selector, in this case focus-out-directive, and then supply the function you wish to trigger on your component.

Example:

<input type='text' focus-out-directive (onFocusOut)='myFunction($event)'/>

like image 24
Googs Avatar answered Sep 19 '22 13:09

Googs