With Angular 2+, component styles are protected and won’t bleed unto other components by default. That’s thanks to the View Encapsulation with Shadow DOM or Shadow DOM emulation. There are still ways however to play around and have a component’s style interact with it’s surrounding with :host, :host-context and /deep/ (now ::ng-deep). There’s also a way to change the behavior for the view encapsulation:
You can use the special :host pseudo-class selector to apply styles in the host component’s template, the one that parent to the current component:
:host {
background-color: #545454;
color: white;
font-size: 1.5em;
}
Specify a selector with :host(selector) to apply the styles only of the selector is present in the host component. In this example the styles are only applied if the host has a .dark class:
:host(.dark) {
background-color: #545454;
color: white;
font-size: 1.5em;
}
With :host-context you can apply styles to the current component based on a condition of any component or html element that’s above itself in the component tree. A common use case is to apply styles if for example a certain class is present on the body element. This is really useful for theming.
In the following example the span elements with class .info will get styled only if a .deep-purple is found somewhere upstream:
:host-context(.deep-purple) span.info {
border: 3px solid hotpink;
border-radius: 12px;
}
With ::ng-deep, styles will be applied to the current component, but also trickle down to the components that are children to the current component in the component tree.
Prior to Angular 4.3, /deep/ or >>> was used instead of ::ng-deep. Both notations have been deprecated by browsers, so ::ng-deep is now the temporary workaround.
In the following example span.info with be style in the current component and it’s children components:
::ng-deep span.info {
border: 3px solid hotpink;
border-radius: 12px;
}
All these pseudo-classes can also be combined for maximum control:
:host-context(.deep-purple) ::ng-deep span.info {
border: 3px solid hotpink;
border-radius: 12px;
}
The view encapsulation can be set to either Native, Emulated (the default) or None in the component’s decorator like this:
@Component({
selector: 'my-app',
...,
encapsulation: ViewEncapsulation.None
})
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!