Angular 2+ HostListener Decorator

Angular 2+ HostListener Decorator

This is my first article on this platform and I really hope it's not the last. lol

So, I want to discuss something in Angular that people really overlook (at least from my experience). Angular as we all know is a Frontend framework and it's really opinionated about many concepts. Think of anything you wanna pull off in your frontend application, there is an angular way of doing it. You can use the various concepts and programming techniques available, but believe me, if you search deep you will discover the prescribed way of doing it in Angular.

One of those techniques/concepts is what I want to write about. We all have been in situations where we have to make our applications listen to some events such as click, window resize etc. And in a way, the application has to respond to those events that are fired up. One way of pulling this off is the use of HostListener decorator.

Decorators are like functions that can be used to add meta-data, properties or functions to whatever they are attached to. There are many types of decorators and you can read more about them here .

So say we need to make our application responsive to changes in window size. Here is a perfect use case for HostListener

Firstly, we create a method that handles that, say we call it onWindowResize

onWindowResize() {

}

Now, we need to add a hostListener decorator to the method. In decorator, we need to provide the kind of event we want to listen to, in this case, it's a 'window:resize' event like so:

import { HostListener } from '@angular/core';

@HostListener('window:resize', ['event'])
onWindowResize() {

}

We can invoke this method in the ngOninit lifecycle

import { OnInit, HostListener } from '@angular/core';

@HostListener('window:resize', ['event'])
onWindowResize() {

}

ngOnInit(){
   this.onWindowResize();
}

This is we telling the application to always listen for the 'window:resize' event. We can then indicate whatever we want to implement on emit of that event. Say we want to hide a section of the application's template when the inner width of the window is below 720px or we want apply a class to a template element at a given window height etc., the use case is endless

 import { OnInit, HostListener } from '@angular/core';

show = true;
@HostListener('window:resize', ['event'])
onWindowResize(event) {
 if(event.target.innerWidth <= 720){
   this.show = false;
 }
}

ngOnInit(){
   this.onWindowResize();
}

There you have it. This is like a basic usage of the HostListener decorator, it can be used to target varieties of events like dragLeave, dragOver, etc like so

@HostListener('dragover', ['$event']) 
dragOver(event) {

  }

Please feel free to drop your comments and opinions about this article. Also reach out on twitter @horlabyc . Thank you