...

/

Handle Events with a Custom Attribute Directive

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 ...