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

后端 未结 8 1145
后悔当初
后悔当初 2020-12-05 01:50

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

@HostListener(\'dragstart\', [\'$event\'])
    onDragStart(ev:Event) {
        co         


        
8条回答
  •  既然无缘
    2020-12-05 02:44

    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 = new EventEmitter();
    
       @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:

提交回复
热议问题