Styles Between Components in Angular 2+

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:

:host

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;
}

:host-context

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;
}

::ng-deep

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;
}

View Encapsulation

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
})
  • Native uses the browser’s native Shadow DOM capabilities. The browser support is still very limited for native support.
  • Emulated is the default behavior and uses an emulated Shadow DOM. It’s most appropriate now because of the majority of common use browsers not supporting Shadow DOM.
  • None doesn’t apply any view encapsulation and styles applied to one component will also have a global effect on the whole app.
  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...