Sub topic 10
ViewEncapsulation.ShadowDom: native style isolation
This chapter assumes you know basic CSS selectors and specificity, can write a standalone Angular component with the @Component decorator, and have read the earlier chapters on Emulated encapsulation and :host. Here you will see how ViewEncapsulation.ShadowDom works, what it changes compared with the default, and what problems to expect.
What ShadowDom encapsulation does
Emulated encapsulation, the default, imitates style isolation. Angular rewrites your selectors and adds generated attributes to elements. The browser knows nothing about it.
ViewEncapsulation.ShadowDom uses the browser's own feature instead. A shadow root is a separate DOM tree attached to a host element. CSS rules outside that tree do not match elements inside it, and rules inside it do not match elements outside it. Angular attaches a shadow root to the component's host element and renders the template inside it.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-widget',
template: `<p class="note">Isolated by a shadow root</p>`,
styles: `.note { color: darkgreen; }`,
encapsulation: ViewEncapsulation.ShadowDom,
})
export class WidgetComponent {}The .note rule is written to a <style> element inside the shadow root. No attribute rewriting happens, so the selector stays .note in the output.
Comparing the three modes
| Aspect | Emulated (default) | ShadowDom | None |
|---|---|---|---|
| Isolation mechanism | Generated attributes added to selectors | Native shadow root | None |
| Global styles reach the component | Yes | No, except inherited properties | Yes |
| Component styles leak out | No, but see the note on child components | No | Yes |
| Where the `<style>` element goes | Document `<head>` | Inside the shadow root | Document `<head>` |
| Browser support needed | Any | Shadow DOM | Any |
Emulated mode isolates only in one direction. Global styles can still change your component. ShadowDom blocks both directions.
How the rendered DOM looks
With the component above on a page, the browser's inspector shows something like this:
<app-widget>
#shadow-root (open)
<style>.note { color: darkgreen; }</style>
<p class="note">Isolated by a shadow root</p>
</app-widget>Angular creates the shadow root in open mode. This means element.shadowRoot returns the root, so tests and scripts can look inside it.
Two details follow from this structure:
- Each instance of the component gets its own
<style>element inside its own shadow root. With Emulated mode, a style is added to the document once and shared by every instance. With ShadowDom the styles are repeated per instance, which costs memory if you render thousands of instances. - Styles added with
styleUrlorstyleUrlsare processed by the build, then placed in the shadow root in the same way as inline styles.
What crosses the shadow boundary
The boundary blocks selectors. It does not block everything.
Inherited properties
Some CSS properties are inherited by default. These include color, font-family, font-size, line-height and visibility. An inherited value flows from the host element into the shadow tree. If the page sets body { font-family: Georgia; }, text inside the shadow root still uses Georgia unless the component sets its own font.
Non-inherited properties such as border, margin, padding and background do not cross.
CSS custom properties
Custom properties (names starting with --) are inherited. This makes them the intended way to configure a shadow-isolated component from outside. A global stylesheet can set a value on the host:
/* styles.css (global) */
app-widget {
--note-color: crimson;
}The component reads it, with a fallback:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-themed-widget',
template: `<p class="note">Themed from outside</p>`,
styles: `.note { color: var(--note-color, darkgreen); }`,
encapsulation: ViewEncapsulation.ShadowDom,
})
export class ThemedWidgetComponent {}If no one sets --note-color, the text is dark green. If a parent does, the parent's value wins. Document the custom properties your component accepts, since they form its public styling interface.
Slotted content
A native shadow root distributes light DOM children through <slot> elements. Angular's <ng-content> is the equivalent for Angular templates. In ShadowDom mode, Angular renders <ng-content> as a real <slot>. Projected nodes stay in the light DOM and are displayed in the slot's position.
This has a consequence. Projected content is styled by the styles of the tree where it lives, not by the component's own styles. A rule such as p { color: red; } inside the shadow root does not match a <p> that a parent projected into a slot. To style projected content from inside the shadow tree, use the ::slotted() pseudo-element:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<section class="panel">
<ng-content />
</section>
`,
styles: `
:host {
display: block;
}
.panel {
border: 1px solid #cbd5e1;
padding: 12px;
}
::slotted(h2) {
margin: 0 0 8px;
font-size: 1.1rem;
}
`,
encapsulation: ViewEncapsulation.ShadowDom,
})
export class PanelComponent {}::slotted() accepts only a simple selector, such as h2 or .title. A compound descendant selector like ::slotted(div p) is invalid. It styles the projected top-level element only, not its descendants.
Host styling in ShadowDom mode
:host and :host(.class) are native shadow DOM selectors here. They work without Angular rewriting them. Using :host inside a ShadowDom component styles the host element, as you saw in the previous chapters.
There is one precedence rule to remember. Styles on the host element from the outer document beat :host rules from inside the shadow root. If a global stylesheet says app-panel { display: flex; }, it overrides :host { display: block; }. This lets the outside world adjust the host. It also means :host is best used for defaults.
:host-context(.dark-theme) is not part of the supported cross-browser standard, so avoid it in ShadowDom components. Use a custom property or a host class binding instead.
Edge cases and gotchas
- Global CSS libraries stop working. Bootstrap, Tailwind utility classes and other global stylesheets do not apply inside a shadow root. A button with
class="btn btn-primary"will be unstyled. Either import the library's styles into the component'sstylesorstyleUrl, or choose a different mode for that component. - Global resets and fonts. Rules like
* { box-sizing: border-box; }stop at the boundary. Add them to the component if you need them. @font-facedoes not load from a shadow root. Declare font faces in a global stylesheet. Once declared, the font family name can be used inside the shadow tree.- Document-level queries do not see inside.
document.querySelector('.note')returns nothing for elements in an open shadow root. In unit tests, query throughfixture.nativeElement.shadowRoot. - Events are retargeted. An event from inside the shadow root appears to a listener outside as coming from the host element, not the inner node. Angular event bindings in the template work as usual.
- Nested components inherit the choice only if they set it. Encapsulation is set per component. A ShadowDom parent containing an Emulated child gives the child a shadow-hosted environment. The child's Emulated styles go to the document head, so they do not reach the child's template, which is inside the parent's shadow root. The style rules end up in the wrong tree. When you nest components, set the same mode through the whole subtree, or test the combination carefully.
- Form and accessibility behavior. Label
forattributes and ARIA references such asaria-labelledbyresolve IDs within one tree. They cannot cross a shadow boundary.
Class and style bindings still work
Template bindings are not affected by encapsulation. They change attributes on elements in the shadow tree, and the shadow tree's own CSS reacts:
import { Component, ViewEncapsulation, signal } from '@angular/core';
@Component({
selector: 'app-meter',
template: `
<div class="bar"
[class.full]="percent() === 100"
[style.width.%]="percent()"></div>
<button type="button" (click)="percent.set(100)">Fill</button>
`,
styles: `
.bar { height: 8px; background: steelblue; }
.bar.full { background: seagreen; }
`,
encapsulation: ViewEncapsulation.ShadowDom,
})
export class MeterComponent {
percent = signal(40);
}The .full class is added to an element inside the shadow root, and the .bar.full rule in the same root matches it.
When ShadowDom is a good choice
Use it when isolation in both directions is a requirement:
- Embeddable widgets. A component that runs inside pages you do not control, where unknown global CSS must not break it.
- Angular Elements. Components exported as custom elements often use ShadowDom so they behave like native web components.
- Design systems used by several frameworks. Native isolation does not depend on Angular's attribute scheme.
Choose another mode when your application relies on a global stylesheet, a utility CSS framework or a third-party component library that styles through global class names. In these cases ShadowDom works against you.
Summary of the model
- Angular attaches an open shadow root to the host element and renders the template and the component's styles inside it.
- Selectors from outside cannot match inside, and selectors from inside cannot match outside.
- Inherited properties and custom properties still cross, so use custom properties as the styling API.
- Projected content lives in the outer tree; style it from the shadow tree with
::slotted()and a simple selector. - Global CSS libraries do not apply, and each instance carries its own copy of the styles.
Exercise
A component uses ViewEncapsulation.ShadowDom. Its template contains <button class="btn btn-primary">Save</button>, and the Bootstrap CSS is loaded in the global styles.css. The button renders as a plain unstyled button. Why does this happen, and give two ways to fix it?
Show answer
The global Bootstrap selectors cannot match elements inside the component's shadow root, so .btn and .btn-primary never apply. Fix 1: import the needed Bootstrap styles into the component through its styles or styleUrl, so the rules live inside the shadow root. Fix 2: switch the component to Emulated (or None) encapsulation so global styles can reach it. A third option is to write the button styles yourself and expose colors through CSS custom properties.
Exercise
A ShadowDom component app-panel contains <ng-content />. A parent projects <h2>Title</h2> into it. The panel's styles include h2 { color: red; }, but the heading stays black. What is wrong, and what rule fixes it?
Show answer
Projected nodes remain in the light DOM, outside the shadow root, so a plain h2 selector inside the shadow root does not match them. Use ::slotted(h2) { color: red; } in the component's styles. ::slotted() takes only a simple selector and styles the projected top-level element, not its descendants.