View Encapsulation
View Encapsulation
mulated
E ✅
Encapsulates styles at the component ✅ Yes ❌ No
(Default) level usingscoped CSS(adds unique
attributes to elements).
ShadowDom ✅
Uses nativeShadow DOMAPI to ✅ Yes ✅ Yes
completely isolate styles.
1️⃣
ViewEncapsulation.Emulated(Default)
📌How It Works?
● A
ngularmodifies class names in the stylesso theyonly apply to the current
component.
● Itprevents styles from affecting other componentsbut still uses the global DOM.
✔Example:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
encapsulation: ViewEncapsulation.Emulated // 👈 Default behavior
})
export class DashboardComponent {}
.dashboard-title[_ngcontent-abc123] {
color: red;
}
✅
Scoped styles→ Only apply to this component.
❌
Not completely isolated→ Still exists in the globalDOM.
2️⃣
ViewEncapsulation.ShadowDom(Native Shadow
DOM)
📌How It Works?
● UsesShadow DOMto completely isolate styles fromthe rest of the application.
✔Example:
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
encapsulation: ViewEncapsulation.ShadowDom // 👈 Uses Shadow DOM
})
export class DashboardComponent {}
✔Generated DOM Structure (Inside Shadow Root):
<app-dashboard>
#shadow-root (closed)
<h1 class="dashboard-title">Dashboard</h1>
</app-dashboard>
✅
Fully isolatedfrom global styles.
❌
External styles (like Bootstrap) won't work insideShadow DOM.
3️⃣
ViewEncapsulation.None(No Encapsulation)
📌How It Works?
● N
o style isolation→ Styles defined in this componentcanaffect the whole
application.
✔Example:
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
encapsulation: ViewEncapsulation.None // 👈 No encapsulation
})
export class DashboardComponent {}
✔Result:
dashboard.component.cssapplyglobally.
● Styles from
✅
Useful for global styles (e.g., themes).
❌
Risky for style conflicts!
🔹 When to Use Which Encapsulation Mode?
Use Case ecommended
R
Encapsulation
❌
Need global styles without isolation (not None
recommended)
🚀 Final Thoughts
🎯Now you have full control over Angular styles!Let me know if you need examples! 😊