Sub topic 18
Binding to the Host Element
Every component renders inside a host element. The host element is the DOM element that matches the component's selector, such as <app-toggle>. So far, your bindings have targeted elements inside a component's own template. This chapter shows how a component or directive can set properties, attributes, classes, and styles on its host element, and listen to events on it, without asking the parent to do that work.
This chapter assumes you already know property, attribute, class, style, and event bindings, signal-based inputs and model(), and the :host selector from the chapter on styling and view encapsulation.
Why bind to the host?
Look at a custom toggle switch rendered as <app-switch>. For accessibility it needs role="switch", an aria-checked value, a tabindex, and keyboard handling. You could wrap everything in an inner <button>. That adds an extra element, though, and the host element is still the box that takes up layout space. You could instead make the parent add these attributes every time it uses the component. Then every usage site has to repeat them, and some will get them wrong.
Host bindings let the component own its outer element. The component sets the attributes and listeners once, in its own metadata, and every instance gets them.
The `host` metadata property
Angular recommends declaring host bindings in the host object of @Component or @Directive. The keys use the same syntax you already use in templates:
| Key form | Meaning | Example key | Example value |
|---|---|---|---|
| `name` | Static attribute | `'role'` | `'switch'` |
| `[prop]` | DOM property binding | `'[tabIndex]'` | `'disabled() ? -1 : 0'` |
| `[attr.name]` | Attribute binding | `'[attr.aria-checked]'` | `'checked()'` |
| `[class.name]` | Toggle one class | `'[class.is-on]'` | `'checked()'` |
| `[style.prop]` | Style binding | `'[style.opacity]'` | `'disabled() ? 0.5 : 1'` |
| `(event)` | Listener on the host | `'(click)'` | `'toggle()'` |
| `(target:event)` | Global listener | `'(document:keydown.escape)'` | `'close()'` |
Values are template expressions evaluated against the component instance, so you can call signals, call methods, and pass $event.
import { Component, input, model } from '@angular/core';
@Component({
selector: 'app-switch',
template: `<span class="knob"></span><ng-content />`,
host: {
'role': 'switch',
'class': 'switch',
'[attr.aria-checked]': 'checked()',
'[attr.aria-disabled]': 'disabled()',
'[tabIndex]': 'disabled() ? -1 : 0',
'[class.is-on]': 'checked()',
'[style.opacity]': 'disabled() ? 0.5 : 1',
'(click)': 'toggle()',
'(keydown.space)': 'toggle(); $event.preventDefault()',
'(keydown.enter)': 'toggle()'
},
styles: `
:host { display: inline-flex; align-items: center; gap: 0.5rem; cursor: pointer; }
:host(.is-on) .knob { background: seagreen; }
.knob { width: 1rem; height: 1rem; border-radius: 50%; background: #999; }
`
})
export class SwitchComponent {
checked = model(false);
disabled = input(false);
toggle() {
if (!this.disabled()) {
this.checked.set(!this.checked());
}
}
}A parent uses it with no extra wiring:
import { Component, signal } from '@angular/core';
import { SwitchComponent } from './switch.component';
@Component({
selector: 'app-prefs',
imports: [SwitchComponent],
template: `
<app-switch [(checked)]="darkMode">Dark mode</app-switch>
<p>Dark mode is {{ darkMode() ? 'on' : 'off' }}.</p>
`
})
export class PrefsComponent {
darkMode = signal(false);
}Because the host bindings read signals, Angular updates aria-checked, the is-on class, and the opacity whenever those signals change. Note how :host(.is-on) pairs with the host class binding. The component sets a class on its own host, and its encapsulated styles react to it.
Host bindings on directives
Attribute directives have no template, so host bindings are their main tool. This directive highlights whatever element it sits on:
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'hovered() ? color() : null',
'(mouseenter)': 'hovered.set(true)',
'(mouseleave)': 'hovered.set(false)'
}
})
export class HighlightDirective {
color = input('khaki', { alias: 'appHighlight' });
hovered = signal(false);
}Usage: <p appHighlight="lightblue">Hover me</p>, with HighlightDirective in the component's imports. A null style value removes the style, which avoids leaving a stale background behind.
Global event targets
Prefix an event with window:, document:, or body: to listen beyond the host:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-dropdown',
template: `
<button (click)="open.set(!open())">Menu</button>
@if (open()) {
<ul><li>Profile</li><li>Sign out</li></ul>
}
`,
host: {
'(document:keydown.escape)': 'open.set(false)',
'(window:resize)': 'onResize($event)'
}
})
export class DropdownComponent {
open = signal(false);
width = signal(window.innerWidth);
onResize(event: UIEvent) {
this.width.set((event.target as Window).innerWidth);
}
}Angular adds these listeners when the component is created and removes them when it is destroyed. That avoids the leak you get when you call addEventListener by hand and forget to clean up.
The decorator forms: `@HostBinding` and `@HostListener`
Older code, and many libraries, use decorators on class members:
import { Component, HostBinding, HostListener } from '@angular/core';
@Component({
selector: 'app-legacy-chip',
template: `<ng-content />`
})
export class LegacyChipComponent {
@HostBinding('class.selected') selected = false;
@HostBinding('attr.role') role = 'option';
@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
this.selected = !this.selected;
}
}These still work. The Angular docs recommend the host object, for three reasons. All host behavior sits in one place in the metadata. It uses the template syntax you already know. And recent Angular versions can type-check host expressions; Angular 20 added the typeCheckHostBindings compiler option for this. With decorators, the arguments to @HostListener are strings that are not checked against the event.
When bindings collide
The parent can bind to the host element too, for example <app-switch role="checkbox">. When the parent's binding and the component's host binding target the same property or attribute, Angular resolves the conflict like this:
| Parent (instance) binding | Host binding | Winner |
|---|---|---|
| Static | Static | Parent instance |
| Static | Dynamic | Dynamic (host) |
| Dynamic | Static | Dynamic (parent) |
| Dynamic | Dynamic | Component's host binding |
Classes and styles behave differently. Angular merges them. A parent's class="wide" and the host's class="switch" plus [class.is-on] all coexist on the element. A conflict only happens when both sides set the same individual class or the same style property.
Common errors and gotchas
- Binding a property that does not exist.
'[ariaChecked]'targets a DOM property, which only some browsers support. For ARIA, prefer'[attr.aria-checked]'. - Forgetting
displayon the host. Custom elements aredisplay: inlineby default. Width, padding, and borders on the host often look wrong until you set:host { display: block; }or a flex value. - Static attributes in quotes. Write
'role': 'switch', not'[role]': 'switch'. The bracket form evaluatesswitchas an expression, and that fails at compile time. - Heavy expressions. Host expressions run on every change detection pass that checks the component. Keep them to simple reads of signals or fields, and use
computed()for anything costly. - Using
ElementRefandRenderer2for simple cases. Setting classes by hand withRenderer2bypasses the collision rules above, and the code is harder to read. Use host bindings unless you need truly imperative DOM work.
Exercise
Write a directive appAutoTitle that sets the host's title attribute to the host element's text content trimmed to 20 characters, and adds the class is-pressed while the mouse button is held down on it. Use the host metadata property and signals.
Show answer
Use ElementRef to read the text once, and signals for state:
import { Directive, ElementRef, inject, signal } from '@angular/core';
@Directive({
selector: '[appAutoTitle]',
host: {
'[attr.title]': 'title',
'[class.is-pressed]': 'pressed()',
'(mousedown)': 'pressed.set(true)',
'(mouseup)': 'pressed.set(false)',
'(mouseleave)': 'pressed.set(false)'
}
})
export class AutoTitleDirective {
private el = inject(ElementRef<HTMLElement>);
title = (this.el.nativeElement.textContent ?? '').trim().slice(0, 20);
pressed = signal(false);
}
The mouseleave handler stops the class from sticking when the user drags off the element before releasing.
Exercise
A parent renders <app-switch [attr.aria-checked]="'mixed'">, and SwitchComponent's host has '[attr.aria-checked]': 'checked()'. Which value ends up on the element, and why?
Show answer
The component's value, checked(). Both bindings are dynamic, and when both are dynamic the component's host binding wins. To let the parent override it, the component should expose an input such as ariaChecked and use it in its own host expression.