Sub topic 3
Styling the host element with :host
This chapter assumes you can write a standalone component with @Component, you know CSS selectors and specificity, and you have seen Emulated view encapsulation. Here you will learn how to style the element that a component is attached to, how the :host selectors work, and how outside styles interact with them.
What the host element is
Every component is attached to an element in the DOM called its host element. For selector: 'app-card', the host is the <app-card> tag that appears in the parent's template. The component's template renders inside that tag.
A component's styles are scoped to its own template, so a plain selector such as .label can only match elements inside the template. The host element is not in the template. It belongs to the parent's template. A rule like app-card { display: block; } inside app-card's own stylesheet would therefore never match anything.
Angular solves this with the :host pseudo-class selector. In a component's styles, :host refers to that component's own host element.
Why you almost always need :host
Custom element tags such as <app-badge> have no default styling. The browser treats them like <span>, which is display: inline. Inline elements ignore width, height, and vertical margins. If your component is a block-level thing such as a card or a panel, it needs this rule:
import { Component } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label"><ng-content /></span>`,
styles: `
:host {
display: inline-block;
}
.label {
padding: 2px 8px;
border-radius: 4px;
background: #e0e7ff;
}
`,
})
export class BadgeComponent {}The :host rule styles the <app-badge> element itself. The .label rule styles the <span> inside the template. Both rules live in the same stylesheet and are both scoped to this component.
Set display on the host of every component you write. Without it, the layout depends on the browser default, and the parent has to compensate.
How :host compiles under Emulated encapsulation
With the default ViewEncapsulation.Emulated, Angular adds generated attributes to elements and rewrites your selectors to match them. The host element gets an attribute like _nghost-ng-c123, and elements in the template get _ngcontent-ng-c123. The exact names change between builds, so never write them yourself.
Your rules are rewritten roughly like this:
| You write | Angular emits (approximately) |
|---|---|
| `:host { ... }` | `[_nghost-ng-c123] { ... }` |
| `.label { ... }` | `.label[_ngcontent-ng-c123] { ... }` |
| `:host(.highlighted) { ... }` | `.highlighted[_nghost-ng-c123] { ... }` |
| `:host-context(.dark) { ... }` | `.dark[_nghost-ng-c123], .dark [_nghost-ng-c123] { ... }` |
Each rewritten selector contains an attribute selector. That raises its specificity by one class level, and it is the source of most host styling surprises, covered below.
Styling the host conditionally with :host(selector)
The function form :host(selector) matches the host only when the host itself also matches the selector inside the parentheses. This is how you style a host according to a class or attribute set on it.
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 host metadata property binds the highlighted class on the host to the highlighted input. The :host(.highlighted) rule then applies when that class is present. Host bindings get their own chapter, so here the point is only that the class and the selector cooperate.
A parent can also set the class directly, either as <app-card class="highlighted"> or with [class.highlighted]="flag" in its own template. :host(.highlighted) matches in both cases, because it only looks at the final DOM.
You can use other selectors inside the parentheses too. Attribute selectors are useful for variants:
:host([size='large']) {
padding: 32px;
}
:host(:hover) {
background: #f1f5f9;
}
:host(:not([disabled])) {
cursor: pointer;
}The argument must be a compound selector, which means no descendant combinators. :host(.a .b) is invalid. To style descendants of a host in a given state, put :host(.a) in front of the descendant selector instead:
:host(.compact) .title {
font-size: 0.875rem;
}Styling based on an ancestor with :host-context()
:host-context(selector) matches the host when the host or any of its ancestors matches the selector. The classic use is theming by a class on <body> or on a wrapper element.
import { Component } from '@angular/core';
@Component({
selector: 'app-panel',
template: `<section class="panel"><ng-content /></section>`,
styles: `
:host {
display: block;
}
.panel {
background: white;
color: #111827;
}
:host-context(.dark-theme) .panel {
background: #111827;
color: #f9fafb;
}
`,
})
export class PanelComponent {}When any ancestor has the class dark-theme, the panel switches colors.
Specificity and who wins
Three kinds of rules can target the same host element. Their specificity under Emulated encapsulation decides the outcome:
| Rule location | Example | Approximate specificity |
|---|---|---|
| Child's own `:host` | `[_nghost-x] { margin: 0 }` | 0,1,0 |
| Global stylesheet, element selector | `app-card { margin: 8px }` | 0,0,1 |
| Parent's component stylesheet | `app-card[_ngcontent-y] { margin: 8px }` | 0,1,1 |
The consequences:
- A global element-selector rule such as
app-card { ... }loses to the child's:hostrule. This surprises people who putapp-card { display: none }instyles.cssand see nothing happen when the card also setsdisplay: blockin:host. - A rule written in the parent's stylesheet for
app-cardwins over the child's:host. This is by design. The host element sits in the parent's template, so the parent has the right to position it, for example with margins or grid placement. - A global rule with a class, like
.wide { ... }, has specificity 0,1,0, the same as:host. The later rule in the cascade wins, and the order depends on how styles are injected. Don't rely on it.
import { Component } from '@angular/core';
import { CardComponent } from './card.component';
@Component({
selector: 'app-dashboard',
imports: [CardComponent],
template: `
<app-card class="spaced">Revenue</app-card>
<app-card class="spaced" [highlighted]="true">Alerts</app-card>
`,
styles: `
app-card.spaced {
margin-bottom: 16px;
}
`,
})
export class DashboardComponent {}The .spaced rule belongs to the parent and styles layout around the child. The child's :host rule styles the child's own box.
Common errors
- Writing the component's own selector, for example
app-card { ... }, in the component's stylesheet. Under Emulated encapsulation it becomesapp-card[_ngcontent-x], which looks for an<app-card>inside the template. Use:host. - Forgetting
displayon the host. Width, height, and vertical margins then behave unexpectedly because the element is inline. - Using
:host .childand expecting it to reach into child components. Emulated encapsulation still blocks styles from crossing into the template of a different component, and:host .childonly matches elements that belong to this component's own template. - Using a descendant combinator inside
:host(...), which is invalid. - Relying on a global
app-card { ... }rule to override:host. It has lower specificity and loses.
Behavior in the other encapsulation modes
- Emulated (default):
:hostis rewritten as described above. - ShadowDom: The component renders inside a native shadow root, and
:hostis the browser's own selector for the shadow host. Outside rules forapp-cardstill apply to the host, because the host lives in the outer document. In the cascade between outer styles and:host, the outer styles win for normal declarations. - None: Angular does not rewrite anything, and the component's styles become global. A
:hostrule then matches nothing useful, because there is no host marker attribute and no shadow root. Use the element selector, such asapp-card { ... }, in that case.
Exercise
A component app-tag has styles: ':host { display: inline-block; margin: 0 }'. Its parent's stylesheet contains app-tag { margin-right: 12px }, and the global styles.css contains app-tag { margin-left: 20px; display: block }. Under Emulated encapsulation, which margin values and which display does the rendered <app-tag> have, and why?
Show answer
The margin-right is 12px, the margin-left is 0, and the display is inline-block. The parent's rule compiles to app-tag[_ngcontent-x], with specificity 0,1,1, which beats the child's :host rule (0,1,0) for margin-right. The global app-tag rule has specificity 0,0,1, so the child's :host rule wins for margin-left (0 instead of 20px) and for display (inline-block instead of block). The global rule applies only to properties that no other rule sets.