Skip to content

the three Angular view encapsulation modes

Here’s an example to illustrate the three Angular view encapsulation modesEmulated, ShadowDom, and None—with a practical use case and their behavior:


👩‍🏫 Example Angular Component: hello-world.component.ts

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-hello-world',
  template: `<h1>Hello World!</h1>`,
  styles: [`h1 { color: red; }`],
  encapsulation: ViewEncapsulation.Emulated  // Change to ShadowDom or None to test
})
export class HelloWorldComponent {}

1. Emulated (Default)

  • Angular adds scoped styles using attributes like _ngcontent-xxx.
  • ✅ Works in all browsers.
  • 🔒 Prevents style bleeding in and out of the component.

HTML Output:

<h1 _ngcontent-c0>Hello World!</h1>

CSS in DOM:

h1[_ngcontent-c0] {
  color: red;
}

🧠 Use when: You want safe, scoped styles without worrying about browser support.


2. ShadowDom

  • Uses the native Shadow DOM API (attachShadow()).
  • 💡 Styles are completely isolated (no leaking in or out).
  • ❗ Only works in modern browsers.

HTML Output:

<app-hello-world>
  #shadow-root (open)
    <style>h1 { color: red; }</style>
    <h1>Hello World!</h1>
</app-hello-world>

🧠 Use when: You’re building web components or custom elements meant to be reusable and self-contained.


3. None

  • Angular applies styles globally—like traditional CSS.
  • ⚠️ Style leaks everywhere, even to other components.
  • ✅ Fastest, but dangerous for large apps.

CSS in DOM:

h1 {
  color: red;
}

🧠 Use when: You need a quick override or integration into legacy global styles—but use sparingly.


📊 Summary Table

Mode Isolation Compatibility Performance Use Case
Emulated Scoped via attrs (_ngcontent) ✅ All browsers 🔹 Slight overhead Default, safe choice
ShadowDom True isolation ❗ Modern browsers only 🔸 Native, efficient Web components
None No isolation ✅ All browsers 🔺 Fastest (but risky) Global overrides, temporary hacks

 

Leave a Reply

Discover more from Sowft | Transforming Ideas into Digital Success

Subscribe now to keep reading and get access to the full archive.

Continue reading