When you build a component, you often want to reuse it across different parts of your application. Its styling should adapt to the container or the surrounding context where it is placed. The :host-context pseudo-selector establishes this link, letting you match component styles against an ancestor or another component.
Further details are available at https://angular.io/guide/component-styles#host-context
Consider a button component used in both the main application and a product component. The button must adjust its appearance for each environment. If either the product component or the main app alters its color scheme, the button should respond accordingly. The desired behavior looks like this:
Let’s implement this using the :host-context selector.
Harnessing :host-context()
The :host-context pseudo-selector creates a styling connection between components, like linking the product component to the my-app component.
//product.component.css
:host-context(my-app.dark) .content {
background-color: black;
color: white;
}
When the my-app component receives the dark class, the product component applies the corresponding styles because the CSS selector matches the ancestor hierarchy.
You can also define several relations for the same component at once, as demonstrated below.
Defining Multiple Relations
We’ve seen how to match a single selector for the background. Now, let’s extend this to multiple selectors with additional rules.
- Apply a white smoke background when
app-producthas thedayclass. - Apply a blue background when
app-producthas the.darkclass. - Apply a pink background when the
my-appcomponent has the.darkclass.
Update the button.component.css file by adding the following lines to target the .btn class selector.
//button.css file.
//Relation with app-product with the day class
:host-context(app-product.day) .btn {
background-color: whitesmoke;
}
//Relation with app-product with the dark class
:host-context(app-product.dark) .btn {
background-color: black;
color: whitesmoke;
}
//relation with my-app with dark class
:host-context(my-app.dark) .btn {
background-color: pink;
color: white;
}
That’s it! The button component is now linked to both its direct parent and the main app component.
You can experiment with the demo to see a small working example and observe how child components respond to these relational styles.
Wrapping Up
That covers it! Hopefully, this gives a helpful nudge toward linking styles between components with the :host-context pseudo-selector.
If you found this useful, please share it!
Photo by Annie Spratt on Unsplash

