Handle Events with a Custom Attribute Directive

Let’s learn how to handle events in the directive.

We recently learned how to create a custom attribute directive and pass data to it. Now, we’ll learn how to handle events. When we say “handle events,” we mean these two actions:

  • Receiving events, such as handling clicks on elements appropriately.
  • Sending events to others, like parent components.

This ability is instrumental to cases in which our directive behaves differently based on user interaction, or if we want to trigger external logic based on a specific condition.

Receive events

In Angular, receiving events subscribe to the DOM events, and can be implemented in different ways. However, the most popular way is to use event binding syntax on elements in the template, like this:

<button (click)="doSomething()"> Click me! </button>

Here, we bind a component’s function doSomething to an event whose target name is click. That’s fine if we have a template and elements inside it, like we have in components. However, we’re currently in the world of directives, so we have no template.

There’s another way, which is to register an event listener function. We can do this by using the HostListener decorator provided by Angular. We’ll focus on implementing it inside the directive, but let’s keep in mind that this approach works similarly for components too.

We start with something straightforward, such as a click event. Then, we create a directive that logs something in the console. That’s it–just a basic implementation!

The HostListener declaration

The HostListener declaration is one of the Angular decorators. It should be provided for a function, just like Input is provided for a variable. The decorator runs the function called the event handler if the event occurs. The event and optional arguments are specified in the HostListener declaration. Let’s look at an example:

@Directive({
  selector: '[appMy]'
})
export class MyDirective {

	@HostListener('click', ['$event'])
	onClick(event: Event) {
		// ... do something on click
	}

}

There are two essential blocks of code detailed below:

  • The first one is the HostListener declaration, which has the event name and the optional array of arguments. In this case, we register for the click event and want to receive the whole event object.
  • The second one is the actual onClick() function. This is the regular function with one argument—the event object. We can do whatever we want inside this function.

Get hands-on with 1200+ tech skills courses.