Angular's default style encapsulation prevents styles from leaking into or out of components. But sometimes, you want your component to adapt based on context provided by external elements, such as a dark
class on the <body>
element. This is where :host-context()
comes in.
What is :host-context()
?
The :host-context()
pseudo-class in Angular allows a component’s style to react to ancestor elements outside the component’s view encapsulation boundary.
It checks if the component is rendered inside an element matching the selector.
:host-context(body.dark) {
.container {
background-color: #222;
color: white;
}
}
This means: "Apply this style if the component is somewhere inside a <body class='dark'>
."
When to Use It
- Theming (e.g. light/dark mode)
- Reacting to global classes or layout wrappers
- Making components context-aware
Key Points
- ✅
:host-context()
checks up the DOM tree, not down. - ✅ It works with Angular's default
ViewEncapsulation.Emulated
. - ❌ It does not work with
ShadowDom
encapsulation. - ❌ Do not repeat the context selector inside the rule block.
Example
:host {
.container {
background: white;
color: black;
}
}
:host-context(body.dark) {
.container {
background: black;
color: white;
}
}
Common Mistake
// ❌ Incorrect
:host-context(body.dark) {
.dark {
background: black;
}
}
This is wrong because .dark
is already in the selector. You don't need to repeat it.
Summary
Use :host-context()
to style Angular components based on their ancestors, such as when a global dark
class is added to the <body>
tag. It’s a powerful tool to make your components responsive to global layout or theming changes.
Top comments (0)