javascript / expert
Snippet
Encapsulating View State with ViewEncapsulation.ShadowDom
ShadowDom encapsulation attaches a genuine Shadow DOM root to the host element, giving true style isolation enforced by the browser rather than Angular's default attribute-based faking with _ngcontent selectors. This matters when the component is embedded into a host page with unknown, potentially conflicting global CSS, since Shadow DOM boundaries block outside styles from leaking in and vice versa. The tradeoff is that global styles like Bootstrap resets no longer apply inside, and CSS custom properties like --badge-color still pierce the boundary intentionally, making them the sanctioned channel for external theming.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Component, ViewEncapsulation } from '@angular/core';@Component({selector: 'app-widget-embed',standalone: true,encapsulation: ViewEncapsulation.ShadowDom,styles: [`:host {display: block;contain: content;}.badge {font-family: system-ui;color: var(--badge-color, #333);}`],template: `<span class="badge"><ng-content></ng-content></span>`,})export class WidgetEmbedComponent {}
angular
Breakdown
1
encapsulation: ViewEncapsulation.ShadowDom,
Switches from Angular's emulated encapsulation to a native browser Shadow DOM root attached to the host element.
2
contain: content;
The CSS containment hint tells the browser this subtree's layout, paint, and style are isolated, letting it skip recalculation work outside the boundary.
3
color: var(--badge-color, #333);
Custom properties are the one styling channel that crosses shadow boundaries, so the host page can still theme this element intentionally.