3
votes

HostListener vs DOM events in Angular 4

So this question is about best practices while coding. Consider I have a component on which I want a blur event. This can be implemented in 2 different ways.

  1. Using the Dom event:

    view.html

    <input (blur)="onBlur($event)"/>
    

    component.ts

    @Component({
    selector: 'input-component'
    template: require('path to view.html')
    })
    export class InputComponent(){
        public onBlur(event: Event){ /*on blur action*/}
    } 
    

    Here I have put a blur event on the input and I have a callback function in my component class.

  2. Using HostListener

    component.ts

    import { HostListener } from '@angular/core';
    @Component({
        selector: 'input-component'
        template: require('path to view.html')
        })
        export class InputComponent(){
            @HostListener('blur', ['$event']) onBlur(event: Event) { /*on blur action*/}
        } 
    

    Here I implemented the same with HostListener. I know that this is used a lot in directive class, but I have seen a lot of examples of component with HostListeners.

My question here is:

  1. Which is the more cleaner and better implementation?
  2. Is it better to stick to the DOM events or go with the angular hooks?
1
I would select DOM event over HostListener unless doing a directive. It is much more clear.DeborahK
Thanks for your comment. I think it makes sense to try to keep the implementation as close as possible to the DOM.ronakvp

1 Answers

2
votes

I would select the Dom event for that particular case. But it depends if you need to listen for events on document level, then you should use the Hostlistener. Also using the HostListener you can optionally define which values should be passed to the decorated method.

Example:

import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';

@Directive({
    selector: '[clickOutside]'
})
export class ClickOutsideDirective {
    constructor(private _elementRef : ElementRef) {
    }

    @Output()
    public clickOutside = new EventEmitter();

    @HostListener('document:click', ['$event.target'])
    public onClick(targetElement) {
    }
}