AngularJs 2 Series: Host Event Binding With @HostListener

Introduction

AngularJs 2 Series: Host Event Binding With @HostListener In one of the previous article Binding The Host Element With @HostBinding, I showed you how to bind property to the host element using @HostBinding decorator. We enabled the highlight directive or attribute on the host element by binding the color to its style.background property. In this article I will use the same Typescript class and show you how you can bind events to the host element. We will use mouse related events (like on hover) to change the background color of the text container. We will use something called as @HostListener decorator or meta data.

First let’s take a look at the existing code which demonstrates the use of @HostBinding decorator.

import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector: '[highlight]'
})
export class HighlightDirective {

	private color = "yellow";
	
	@HostBinding('style.backgroundColor') get getColor() {
		return this.color;
	}
	
	constructor() {
	}

}

We already saw how to render a yellow color to the element hosting this highlight directive using @HostBinding decorator. Now we will change the color from yellow to green on mouse hover. This will be achieved using @HostListener decorator.

Using @HostListener

The @HostListener decorator can be used to bind an event on the hosting element, in our case, the element hosting the highlight attribute. The decorator is prefixed to a method which is invoked upon the occurrence of an event. Let’s look at the revised code that makes use of @HostListener decorator.

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

@Directive({
  selector: '[highlight]'
})
export class HighlightDirective {

	private color = "yellow";
	
	@HostListener('mouseenter') onMouseEnter() {
		this.color = 'green';
	};
	
	@HostListener('mouseleave') onMouseExit() {
		this.color = 'yellow';
	};

	@HostBinding('style.backgroundColor') get getColor() {
		return this.color;
	}
	
	constructor() {
	}

}

The above code is pretty self explanatory. We are using the same directive class with the highlight attribute. We have added @HostListener decorator which accepts the name of the event to bind to the hosting element. The decorator is prefixed to a property or method that will be invoked on the occurance of the specified event. We will need two events viz mouseenter and mouseleave. The mouseenter event will trigger onMouseEnter() method which will change the background color to green and the mouseleave event will trigger onMouseExit() method which will restore back the color to yellow.

Upon running the application, and hovering the mouse pointer over the text you should see the desired output.

Leave a Reply

Your email address will not be published. Required fields are marked *