Sub topic 5
Reacting to events and binding host properties
What this chapter assumes
This chapter assumes you can write a standalone Angular component, use property and event binding in a template, and read TypeScript decorators. You should already have a directive with an attribute selector, applied through a component's imports array. The earlier chapters in this tutorial covered that.
So far a directive could only change its host element once, in its constructor. That is rarely what you want. Real directives react to the user (hover, focus, click, key presses) and keep the element's styles, classes, and attributes in sync with their own state. Angular gives you two mechanisms for this:
- Host event listeners run directive code when the host element, or
windowordocument, emits an event. - Host bindings keep a property, class, style, or attribute of the host in sync with an expression on the directive.
Host event listeners
With @HostListener
@HostListener decorates a method and ties it to an event on the host element. The directive below uses it together with Renderer2 from the previous chapter.
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');
}
}Angular subscribes when it creates the directive and unsubscribes when the host element is destroyed. You never call addEventListener or removeEventListener yourself.
To receive the event object, pass an argument list as the second parameter:
@HostListener('keydown', ['$event'])
onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
// react to Escape
}
}$event is the only special name. You can also pass properties of it, such as '$event.target'.
With the host metadata property
The same listeners can be declared in the host property of the decorator. Angular's style guide prefers this form to the decorators. All the declarations sit in one place, and the directive class stays free of decorators on its members.
import { Directive } from '@angular/core';
@Directive({
selector: 'input[appSelectOnFocus]',
host: {
'(focus)': 'selectAll($event)',
},
})
export class SelectOnFocusDirective {
selectAll(event: FocusEvent) {
(event.target as HTMLInputElement).select();
}
}The key is the event name in parentheses, and the value is a template statement that runs when the event fires. It is evaluated against the directive instance, so selectAll refers to the method above. The selector input[appSelectOnFocus] limits the directive to <input> elements. This makes the HTMLInputElement cast safe.
Key filters and global targets
Event names can carry extra information:
(keydown.enter)fires only for the Enter key. Modifiers combine, as in(keydown.control.s).(window:resize)and(document:click)listen onwindowordocumentinstead of the host element.
The global form is how a click-outside directive works. Angular attaches the listener when the directive is created and removes it when the directive is destroyed, so it cannot leak.
Host bindings
A host binding is a property binding whose target is the host element. It is declared in the same host object, with the target in square brackets and an expression on the directive as the value.
import { Directive, signal } from '@angular/core';
@Directive({
selector: '[appPressable]',
host: {
'[class.pressed]': 'pressed()',
'[attr.aria-pressed]': 'pressed()',
'(mousedown)': 'pressed.set(true)',
'(mouseup)': 'pressed.set(false)',
'(mouseleave)': 'pressed.set(false)',
},
})
export class PressableDirective {
readonly pressed = signal(false);
}Applied as <button appPressable>Save</button>, this directive toggles a pressed class and an aria-pressed attribute on the button. It also adds a user-visible hook for assistive technology.
The common binding targets are:
| Target syntax | What it sets | Example expression |
|---|---|---|
| `[class.name]` | Adds or removes one class | `active()` |
| `[style.property]` | One inline style | `color()` |
| `[style.width.px]` | An inline style with a unit | `width()` |
| `[attr.name]` | An HTML attribute | `role` string |
| `[property]` | A DOM property | `tabIndex` number |
Use attr. for attributes with no matching DOM property, such as aria-* and data-*. Without the prefix, Angular looks for a property of that name on the element and reports an error if none exists.
Binding to a signal-driven style
The next directive combines a host binding, two listeners, and an input. The input shares the directive's selector name, so a value can be written directly on the attribute. Inputs get their own treatment in the next chapter, so read the input() line as "a value from the template, with a default".
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);
}<p appHighlight>Default yellow on hover</p>
<p appHighlight="lightblue">Light blue on hover</p>The directive never touches the DOM. The listeners change a signal, and the binding turns the signal into a style. That is the pattern to aim for: events change state, and bindings render state.
Two details matter here:
- When the expression returns
null, Angular removes the inline style. This is whynullis used for the inactive state, rather than an empty string or a hard-coded "transparent". - The string
"yellow"sits inside single quotes in the TypeScript source, so the expression uses double quotes. Either quote style works inside a host expression.
How the pieces fit together
The listener runs first and only updates state. The binding is re-evaluated in the next change detection pass, and the DOM update follows. Because the directive owns the state, any other code that sets active gets the same rendering for free.
@HostListener and @HostBinding versus host metadata
Both styles produce the same compiled result. @HostBinding('class.pressed') isPressed = false; is equivalent to '[class.pressed]': 'isPressed'.
| Concern | Decorators | `host` metadata |
|---|---|---|
| Where declarations live | Scattered across the class | One block in the decorator |
| Expressions | Property or method name only | Any template expression |
| Works with signals | Needs a getter that calls the signal | Call the signal directly: `'[class.on]': 'on()'` |
| Recommended by the Angular style guide | No | Yes |
Pick one style per project. Mixing them in a single directive works, but readers then have to look in two places.
Edge cases and gotchas
Several directives on one element. Each directive registers its own listeners and bindings. Two directives that bind [style.backgroundColor] on the same element conflict. Angular applies a fixed precedence, but relying on it is fragile. Give each directive a distinct style property or class.
Bindings run on every change detection pass. Keep host expressions cheap. Call signals and simple conditions, not methods that do real work.
Frequent global events. A (window:resize) or (document:mousemove) listener causes a change detection pass on every event, even when your handler changes nothing. A signal set to its current value does not notify consumers, but the listener itself still triggers the pass. For high-frequency events, handle only the cases you need, or throttle the work.
Hover is not enough. Keyboard users never fire mouseenter. If a directive signals state visually, listen for focus and blur too. The directive below adds a narrow-viewport class based on the window width and uses DOCUMENT instead of the bare window global. This keeps it safe on the server, which you will meet again in the pitfalls chapter.
import { Directive, inject, signal } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Directive({
selector: '[appCompact]',
host: {
'[class.compact]': 'compact()',
'(window:resize)': 'update()',
},
})
export class CompactDirective {
private doc = inject(DOCUMENT);
readonly compact = signal(this.isNarrow());
update() {
this.compact.set(this.isNarrow());
}
private isNarrow(): boolean {
return (this.doc.defaultView?.innerWidth ?? 1024) < 600;
}
}Choosing the right tool
- Use a host binding when the host's appearance follows from the directive's state: classes, styles, ARIA attributes.
- Use a host listener when the directive must react to something the user or browser does.
- Use
Renderer2orElementReffor work that bindings cannot express, such as callingfocus()orselect()on the element, or reading its size. - Avoid doing in a listener what a binding can do. A listener that calls
setStyleworks, but a signal plus a binding is shorter, is easier to test, and stays correct when the state changes from another source.
Exercise
A directive uses '(mouseenter)': 'active.set(true)' and '[style.backgroundColor]': 'active() ? "yellow" : null'. Why return null for the inactive state instead of an empty string or a color like "white"?
Show answer
When a style binding evaluates to null, Angular removes the inline style from the element, so the element returns to whatever its stylesheet defines. A hard-coded "white" would override the stylesheet and hide any background the page intended. An empty string may also work, but null is the documented way to clear a binding.
Exercise
Write the host metadata for a directive named appFocusRing that adds the CSS class focus-visible-ring to its host while the host has keyboard focus, using a signal called focused. Which events do you need?
Show answer
Use the focus and blur events plus a class binding: host: { '[class.focus-visible-ring]': 'focused()', '(focus)': 'focused.set(true)', '(blur)': 'focused.set(false)' }, with readonly focused = signal(false); in the class. Both events are needed so the class is removed when focus leaves.