Sub topic 8
Setting host classes and styles with host bindings
This chapter assumes you can write a standalone Angular component, use signals and input(), and read CSS selectors including specificity. It also assumes you have seen :host in a component stylesheet. Here you will learn how a component sets classes, styles and attributes on its own host element, and which mistakes to avoid.
What the host element is
Every component is attached to an element that matches its selector. For selector: 'app-card', the <app-card> tag in the parent's template is the host element. The component's own template renders inside it.
The host sits on a boundary. The parent's template creates it, so the parent can bind to it. The component's class also knows things about itself, such as inputs and state, that should affect how the host looks. Host bindings let the component own that logic instead of asking every parent to repeat it.
You already know that :host selects the host element from inside the component's stylesheet. That handles styles that are always on. Host bindings handle styles that depend on state. The two work together: a binding adds a class to the host, and :host(.class) styles it.
The host metadata property
The host property of the @Component decorator maps host element properties to expressions on the component class. The keys use the same syntax as template bindings, written as strings.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-card',
template: `<ng-content />`,
styles: `
:host {
display: block;
padding: var(--card-padding, 16px);
background: var(--card-background, white);
}
:host(.highlighted) {
outline: 2px solid orange;
}
`,
host: {
'[class.highlighted]': 'highlighted()',
},
})
export class CardComponent {
highlighted = input(false);
}The key '[class.highlighted]' is a class binding. The value 'highlighted()' is an expression evaluated against the component instance. When the highlighted input is true, Angular adds the highlighted class to <app-card>. When it is false, Angular removes it. Because the input is a signal, the binding updates when the input changes.
A parent uses it like this:
<app-card [highlighted]="selected()">Order #1042</app-card>The parent passes state, and the card decides what that state means for its host element.
The kinds of host bindings
The host object supports the same binding forms you use in templates.
| Key form | Example | Effect |
|---|---|---|
| Single class | `'[class.active]': 'isActive()'` | Adds or removes one class |
| Class list | `'[class]': 'classes()'` | Sets classes from a string, array or object |
| Single style | `'[style.width.px]': 'width()'` | Sets one style property, with an optional unit |
| Style map | `'[style]': 'styles()'` | Sets several style properties from an object |
| Attribute | `'[attr.aria-busy]': 'busy()'` | Sets or removes an attribute |
| Property | `'[tabIndex]': 'tab()'` | Sets a DOM property |
| Static attribute | `'role': 'button'` | Sets a fixed attribute value, with no brackets |
| Event | `'(keydown.enter)': 'activate()'` | Listens to an event on the host |
Static entries have no brackets and their values are plain strings. For a fixed class, write 'class': 'app-card'. For a fixed attribute, write 'role': 'button'. Angular sets these once, when the host is created.
Here is a button-like component that uses several forms together:
import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-toggle',
template: `<ng-content />`,
styles: `
:host {
display: inline-block;
padding: 4px 12px;
border: 1px solid #94a3b8;
cursor: pointer;
}
:host(.on) {
background: #16a34a;
color: white;
}
:host([aria-disabled='true']) {
opacity: 0.5;
cursor: not-allowed;
}
`,
host: {
role: 'switch',
'[class.on]': 'checked()',
'[attr.aria-checked]': 'checked()',
'[attr.aria-disabled]': 'disabled()',
'[attr.tabindex]': 'disabled() ? -1 : 0',
'(click)': 'toggle()',
'(keydown.space)': 'toggle(); $event.preventDefault()',
},
})
export class ToggleComponent {
checked = input(false);
disabled = input(false);
changed = output<boolean>();
toggle() {
if (!this.disabled()) {
this.changed.emit(!this.checked());
}
}
}The component never changes checked itself. The parent owns that state, so the host stays in sync with the input. The accessibility attributes and the visual class come from the same signal, so they cannot drift apart.
Host bindings versus parent bindings
A parent can also bind classes directly on the component tag:
<app-card [class.highlighted]="selected()">Order #1042</app-card>Both approaches work, and they combine. Angular merges the classes from the parent's binding, the component's host binding and any static class attribute. A few differences guide the choice:
- Use a host binding when the class depends on the component's own state or inputs. The logic lives in one place.
- Use a parent binding when the parent decides on a class for layout, such as a grid placement or a spacing helper. The component should not know about its surroundings.
- A component should avoid host bindings for layout that belongs to the parent, such as
marginorgrid-area. Let the parent set those.
If two bindings write the same class name, the result depends on binding precedence. Angular gives host-binding and template-binding sources a defined order, but relying on it makes code hard to read. Give each class one owner.
Host bindings versus @HostBinding and @HostListener
Older code uses decorators for the same job:
@HostBinding('class.highlighted') get isHighlighted() { return this.highlighted(); }
@HostListener('click') onClick() { /* ... */ }The Angular style guide now recommends the host property instead. The decorators still work, but the host object keeps all host behavior in one visible block next to the selector and template. It also avoids a getter that Angular evaluates on every change detection pass. If you maintain a codebase that uses the decorators, you do not need to migrate in one step. The two forms can coexist in the same project, but keep one form per component.
How the host interacts with encapsulation
Under the default Emulated encapsulation, Angular adds a generated attribute, such as _nghost-abc-c1, to the host element, and a matching _ngcontent-abc-c1 attribute to elements in the component's template. The compiler rewrites :host to target the first attribute. That is why :host(.highlighted) matches only the component's own host and not any .highlighted element elsewhere.
Host bindings are not scoped in the same way. A binding like '[class.highlighted]' writes a plain class name to the DOM. Any global stylesheet or parent stylesheet that has a .highlighted rule can match the host. This has two consequences:
- A class name set through a host binding can collide with global classes. Prefer specific names, such as
card-highlighted, if your app has a broad global stylesheet. - A parent can style the host from outside, since the host element belongs to the parent's template as well. Under Emulated encapsulation, a parent stylesheet rule for
app-cardapplies to the host, because the parent's scoping attribute is also on that element.
The next diagram shows where each source of styling reaches the host element.
Precedence and specificity
When several sources set the same property, the usual CSS cascade decides the visible result. Two points matter for host elements:
:hosthas the specificity of a pseudo-class, which is low. A parent's rule such asapp-card { padding: 8px; }has the specificity of an element selector. Check the rule order and specificity of both before assuming one wins. In practice, parent rules often override:hostdefaults, which is the behavior you want: the component sets a default and the parent can adjust it.- Inline styles from a style host binding override selector-based rules. A binding such as
'[style.width.px]': 'width()'writes to the element'sstyleattribute, so a:host { width: 100px; }rule loses to it.
For values that a parent should be able to override, prefer a CSS custom property with a fallback over an inline style binding. A parent cannot easily beat an inline style from outside, but it can set --card-padding freely.
/* styles.css (global) */
app-card {
--card-background: #f8fafc;
--card-padding: 24px;
}The custom properties inherit into the component's encapsulated styles, so the var(--card-padding, 16px) rule in CardComponent picks them up. You can also drive a custom property from a host binding: '[style.--card-accent]': 'accent()'. This gives you dynamic values and keeps the actual declaration in the stylesheet.
Common errors
- Missing quotes around the value. In the
hostobject, both key and value are strings.'[class.on]': checked()is wrong, because it calls a function at decoration time. Write'[class.on]': 'checked()'. - Forgetting the call on signals.
'[class.on]': 'checked'binds the signal object, which is always truthy. Write'checked()'. - Using
:hostfor conditional state without a class.:host(.on)needs something to add theonclass. Without the binding, the rule never matches. - Expecting host classes to be scoped. The class name is global in the DOM, as described above.
- Binding the same class from two places. The parent and the component both writing
[class.active]leads to confusing results. Choose one owner. - Heavy expressions. Host binding expressions run during change detection. Keep them to a signal read or a simple ternary, and put heavier work into a
computed(). - Setting a style binding when a class would do. Static visual design belongs in the stylesheet. Use a
stylebinding only for values that come from data, such as a width in percent.
A cleaner pattern for several related classes is to compute them once:
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-alert',
template: `<ng-content />`,
styles: `
:host { display: block; padding: 8px 12px; }
:host(.alert-info) { background: #dbeafe; }
:host(.alert-error) { background: #fee2e2; }
:host(.alert-compact) { padding: 2px 6px; }
`,
host: {
'[class]': 'hostClasses()',
role: 'alert',
},
})
export class AlertComponent {
severity = input<'info' | 'error'>('info');
compact = input(false);
hostClasses = computed(() => ({
'alert-info': this.severity() === 'info',
'alert-error': this.severity() === 'error',
'alert-compact': this.compact(),
}));
}The [class] binding accepts an object where each key is a class name and each value decides whether the class is present. Classes added by the parent or by a static class attribute are kept, because Angular merges the sources and does not replace the whole attribute.
Summary of when to use what
| Need | Tool |
|---|---|
| Always-on look of the host | `:host { ... }` in the component stylesheet |
| Look that depends on component state | Host class binding plus `:host(.class)` |
| Value that comes from data | Host style binding such as `'[style.width.px]'` |
| Value a parent should be able to override | CSS custom property with a fallback |
| Accessibility attributes and roles | Static or `[attr.*]` host entries |
| Layout placement | The parent's template or stylesheet |
Exercise
A StatusDotComponent has a status = input<'online' | 'offline'>('offline') input. You want its host element to get the class online only when the status is 'online', and you want :host(.online) to turn the background green. Write the host metadata entry. Then explain why '[class.online]': 'status() === "online"' works but '[class.online]': 'status === "online"' does not.
Show answer
Use host: { '[class.online]': 'status() === "online"' }, and in the styles add :host(.online) { background: green; }. status is a signal, a function object. Without the call, the expression compares the signal object itself to a string, which is never equal, so the class is never added. Calling status() reads the current value, and Angular re-evaluates the binding when the signal changes.
Exercise
A component sets '[style.width.px]': 'width()' on its host. A parent wants a narrower width and writes app-panel { width: 100px; } in its own stylesheet, but it has no effect. Why, and what change to the component would let the parent override the width?
Show answer
A style host binding writes an inline style on the element, and inline styles beat selector-based rules from a stylesheet. To let the parent override it, put the width in the component stylesheet as :host { width: var(--panel-width, 300px); } and, if the value comes from data, bind the custom property with '[style.--panel-width.px]'. The parent can then set --panel-width or, where the host rule is not inline, a normal width rule.