Sub topic 5
Reacting to events and binding host properties
This chapter assumes you can write a standalone attribute directive with @Directive and apply it through a component's imports array. It also assumes you know Angular property and event binding. Here you will make a directive react to events on its host element and update the host's properties.
The host element
The host is the element that carries the directive's attribute. A directive can do two things with it:
- Listen to events the host raises, such as
mouseenterorclick. - Bind host properties, such as styles, classes, and attributes, to values that the directive owns.
Angular offers two syntaxes for each. The first is the host metadata property of @Directive. The second is the decorators @HostListener and @HostBinding. The host property is the one the Angular style guide currently prefers. You will still meet the decorators in existing code.
Listening with @HostListener
@HostListener attaches a class method to a host event. Angular adds the listener when the directive is created and removes it when the directive is destroyed.
import { Directive, ElementRef, HostListener, Renderer2, inject } from '@angular/core';
@Directive({
selector: '[appHover]',
})
export class HoverDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
@HostListener('mouseenter')
onEnter() {
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'lightgray');
}
@HostListener('mouseleave')
onLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'background-color');
}
}The directive writes to the DOM through Renderer2 instead of touching nativeElement.style directly. To read the event object, pass ['$event'] as the second argument, as in @HostListener('click', ['$event']).
Declaring everything in host metadata
Writing to the DOM imperatively works, but you must remember to undo each change. A host binding states the rule once, and Angular keeps the DOM in sync with it. The next version holds the hover state in a signal and binds the style to it.
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'active() ? (color() || "yellow") : null',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
active = signal(false);
}The host object uses the same conventions as a template:
- A key in square brackets, such as
'[style.backgroundColor]', is a property, style, class, or attribute binding. The value is an expression evaluated against the directive instance. - A key in parentheses, such as
'(mouseenter)', is an event listener. The value is a statement that runs when the event fires. - You can bind other targets too, for example
'[class.active]': 'active()'or'[attr.aria-pressed]': 'active()'.
The color input shares the selector name through alias: 'appHighlight'. That lets you write the value on the directive attribute itself. Inputs get their own chapter, so treat it as given here.
Use the directive like this:
<p appHighlight>Default yellow on hover</p>
<p appHighlight="lightblue">Light blue on hover</p>When active() is false, the expression returns null. A null value for a style binding removes the style, so the host returns to its original look without any cleanup code.
Choosing between the two styles
| Need | Prefer |
|---|---|
| Static or signal-driven style, class, or attribute | `host` metadata binding |
| Simple event that calls a method or sets a signal | `host` metadata listener |
| Existing code that already uses decorators | `@HostListener` and `@HostBinding` |
| Listening on `document` or `window` | Either, with a `document:` or `window:` prefix |
Common errors
- Quotes in expressions. The whole expression is a string, so use the other quote type inside it, as in
"yellow"inside single quotes. - A style that never goes away. Imperative code must remove what it set. A binding that evaluates to
nullremoves it for you. - A missing
$event. The listener'(click)': 'onClick($event)'passes the event.'(click)': 'onClick()'does not. - Listeners that stay attached. Add global listeners with the
document:prefix, as in'(document:click)'. Angular removes them with the directive. CallingaddEventListeneryourself puts that cleanup on you.
Exercise
A directive's host metadata contains '[class.active]': 'on()' and '(click)': 'on.set(!on())', where on is a signal(false). What happens to the host element's class list after two clicks?
Show answer
After the first click on() becomes true and Angular adds the class "active" to the host. After the second click on() becomes false and Angular removes the class, so the host ends with no "active" class. The binding handles both the adding and the removing.