Sub topic 5
Choosing a ViewEncapsulation mode
This chapter assumes you can write a standalone component with @Component, that you know CSS selectors and specificity, and that you have seen the default Emulated encapsulation scope a component's styles. Here you compare the three modes Angular offers, learn what each one does to the DOM, and learn how to pick one.
What a ViewEncapsulation mode controls
Every component has an encapsulation metadata property. It decides how the styles in styles or styleUrl relate to the rest of the page, in both directions:
- Outbound: can this component's CSS affect elements outside its template?
- Inbound: can global CSS or a parent's CSS affect elements inside its template?
Angular provides three values in the ViewEncapsulation enum.
| Mode | Outbound leak | Inbound leak | Mechanism |
|---|---|---|---|
| `Emulated` (default) | No | Yes, global styles still apply | Angular rewrites selectors with generated attributes |
| `ShadowDom` | No | No, apart from inherited properties | Browser-native shadow root |
| `None` | Yes | Yes | Styles are added to the page unchanged |
Emulated is a one-way barrier. A component's rules cannot escape, but global rules such as p { margin: 0 } still reach into the component. ShadowDom blocks both directions. None removes the barrier.
Emulated: the default
Under Emulated, Angular adds a generated attribute to each element in the component's template, such as _ngcontent-ng-c123. It also rewrites each CSS selector in the component so that it requires that attribute. The host element receives a matching _nghost-ng-c123 attribute, which is what :host is rewritten to target.
Take the badge component:
import { Component } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label"><ng-content /></span>`,
styles: `
:host {
display: inline-block;
}
.label {
padding: 2px 8px;
border-radius: 4px;
background: #e0e7ff;
}
`,
})
export class BadgeComponent {}The browser receives roughly this CSS and markup (the attribute names vary per build):
[_nghost-ng-c123] {
display: inline-block;
}
.label[_ngcontent-ng-c123] {
padding: 2px 8px;
border-radius: 4px;
background: #e0e7ff;
}<app-badge _nghost-ng-c123>
<span class="label" _ngcontent-ng-c123>New</span>
</app-badge>Four consequences follow from this implementation:
- Specificity rises by one attribute selector.
.labelbecomes.label[_ngcontent-ng-c123], which beats a plain global.labelrule. A global stylesheet can still win with!importantor a higher-specificity selector. - Projected content belongs to the parent. Elements passed through
<ng-content />carry the parent's attribute, not the badge's. A.labelrule in the badge does not match content a parent projects into it. - Child components are not reached. A rule in a parent cannot style elements inside a child's template, because those elements carry the child's attribute. Only the child's host element carries a parent attribute, so a parent can style that element.
- There is no real isolation. Global CSS, including inherited properties and CSS from
styles.css, still applies inside the component.
ShadowDom: browser-native isolation
With ViewEncapsulation.ShadowDom, Angular attaches a shadow root to the host element and renders the template inside it. The browser enforces the boundary, and Angular does not rewrite selectors.
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 {}What changes in practice:
- A global
p { color: red; }does not affect the<p>inside the widget. - The
.noterule does not leak out. - Inherited properties such as
color,font-familyandline-heightand all CSS custom properties still pass through the boundary. This is why custom properties are the standard way to theme a ShadowDom component. - Component styles are placed inside the shadow root, so they are scoped natively.
- Global resources you may expect inside the component, such as a utility CSS framework or a global icon font class, do not apply. You must import them into the component's styles or provide them some other way.
- Selectors like
document.querySelector('.note')no longer find elements inside the component. Testing tools and browser extensions that rely on global queries need to pierce shadow roots.
ShadowDom is the right fit for widgets that are embedded in pages you do not control, and for Angular Elements-style components distributed to other applications. It is usually a poor fit for an application where every component should share a global design system, since that system's CSS stops applying.
None: styles that leak on purpose
ViewEncapsulation.None turns scoping off. Angular adds the component's styles to the document as written, with no attributes and no shadow root.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-markdown-view',
template: `<div class="markdown" [innerHTML]="html"></div>`,
styles: `
.markdown h2 { margin-top: 1.5rem; }
.markdown code { background: #f1f5f9; }
`,
encapsulation: ViewEncapsulation.None,
})
export class MarkdownViewComponent {
html = '<h2>Title</h2><p>Use <code>npm</code>.</p>';
}This example is a legitimate use. Elements created through [innerHTML] do not receive Angular's _ngcontent attribute, so Emulated rules cannot match them. With None, the selectors apply to any matching element in the document.
Points to know before using it:
- Styles are global and persistent. Once the component is created, its styles are added to the document. A later component rendering a
.markdown h2is affected too. - Order decides conflicts. Equal-specificity rules are resolved by the order in which the stylesheets are added, which depends on which components were created first. That order can change when you reorder routes or lazy-load a module.
- Always namespace the selectors. A rule like
h2 { ... }in aNonecomponent restyles everyh2in the app. Prefix with a class unique to the component, as above. :hoststill works as a selector in the stylesheet source, but it has no scoping effect. It is better to target the element with its tag name, for exampleapp-markdown-view { display: block; }.
Mixing modes in one application
Modes are per component. The first element of a hierarchy does not force the setting on its children. A common pattern is to leave most components Emulated, choose None for one component that renders untrusted or generated HTML, and use ShadowDom for a single embeddable widget.
You can also set a default for all components in an application. Provide the ViewEncapsulation default through the bootstrapApplication options or, for the ng build system, set "inlineStyleLanguage" and other style options in angular.json. For the encapsulation default itself, the usual approach is to set it on each component, which keeps the choice visible where the styles live.
Edge cases and gotchas
- Projected content and
None. If you need a child to style projected content, aNonerule is one option, but a CSS custom property on the child's host is almost always cleaner. - Third-party components. A library component with Emulated styles cannot be restyled by your component's rules. Use its documented custom properties, a global rule, or, as a last resort,
:host ::ng-deep, covered in a later chapter. - Style duplication. Under ShadowDom each instance gets its own copy of the styles in its own root. For a list of hundreds of ShadowDom items, this costs memory. Emulated and None share one
<style>element. - Server-side rendering. Emulated and None work with SSR without extra setup. ShadowDom needs declarative shadow DOM support to render on the server, which varies by Angular version, so check the version you use before choosing it for server-rendered pages.
- Changing modes later. Moving from Emulated to ShadowDom can silently remove global styles from a component. Moving from Emulated to None can make the component's rules leak. Review each one when you change modes.
A decision procedure
Use these questions in order:
- Does the component belong to an application that shares a global design system? Keep Emulated.
- Does it render HTML that Angular did not create, such as
[innerHTML]output or DOM from a third-party library, and does it need to style that HTML? Use None with namespaced selectors, or style the output from a global stylesheet instead. - Does it ship into a page you do not control, or must it be guaranteed isolated from page CSS? Use ShadowDom and expose theming through custom properties.
- Does a parent only need to change a few values in a child? Do not change the mode. Expose CSS custom properties on the child.
Exercise
A team adds encapsulation: ViewEncapsulation.ShadowDom to a component in an app whose styles.css defines .btn { background: navy; }. After the change, buttons with class btn inside that component lose their background. Why did this happen, and name two ways to fix it that keep ShadowDom?
Show answer
ShadowDom isolates the component's template from global CSS, so the .btn rule in styles.css no longer reaches elements inside the shadow root (it applied before under Emulated, where global styles reach in). Two fixes: (1) define the .btn rule, or an equivalent, in the component's own styles so it is placed inside the shadow root, or (2) have the global stylesheet define CSS custom properties, such as --btn-background, on the host or an ancestor, since custom properties inherit through the boundary, and use background: var(--btn-background, navy) in the component's styles.
Exercise
In an Emulated component, a rule .label { color: red; } does not color a <span class="label"> that a parent projects through <ng-content />. Explain the cause and give a fix that does not use ViewEncapsulation.None.
Show answer
Projected elements are created by the parent's template, so they carry the parent's _ngcontent attribute, not the child's. The child's rewritten selector .label[_ngcontent-child] therefore does not match them. Fix: put the rule in the parent's styles, where the attribute matches, or have the child expose a custom property, such as color: var(--label-color, inherit) on its host, and let the parent set --label-color.