🛡️
Component Deep Dive

View Encapsulation

CSS Scoping Mechanism
💡 View encapsulation ek soundproof room jaisa hai — har component apna khud ka "room" hai, uski awaazein (CSS styles) bahar nahi jaati, bahar ki awaazein andar nahi aati — default behavior, lekin doors khol bhi sakte ho zaroorat par.

ViewEncapsulation.Emulated (DEFAULT) — Angular fake scoping create karta hai (unique attributes add karke), CSS ko component tak "emulate" karta hai limited karna. ViewEncapsulation.None — koi scoping nahi, styles GLOBALLY apply hoti hain (careful se use karo). ViewEncapsulation.ShadowDom — asli browser Shadow DOM use karta hai, true isolation.

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

@Component({
  selector: 'app-widget',
  templateUrl: './widget.component.html',
  styleUrls: ['./widget.component.css'],
  encapsulation: ViewEncapsulation.Emulated   // default, likhna optional
})
export class WidgetComponent { }

// Rendered HTML mein automatically unique attributes:
// <div _ngcontent-abc123>...</div>
// CSS bhi automatically scoped: div[_ngcontent-abc123] { ... }
🛡️
View encapsulation ek soundproof room jaisa hai — har component apna khud ka "room" hai, uski awaazein (CSS styles) bahar nahi jaati, bahar ki awaazein andar nahi aati — default behavior, lekin doors khol bhi sakte ho zaroorat par.
1 / 2
⚡ Quick Recap
  • Emulated (default) = fake scoping, unique attributes se
  • None = global styles, koi isolation nahi
  • ShadowDom = true browser-level isolation
On this page (2 subtopics)

:host pseudo-class component ke ROOT element (jo <app-xyz> tag khud hai) ko style karta hai — normal CSS selectors component ke ANDAR ke elements ko target karte hain, :host component ke apne tag ko.

/* my-card.component.css: */
:host {
  display: block;
  border: 1px solid #ddd;
  border-radius: 8px;
}

:host(.highlighted) {
  border-color: gold;   /* jab parent <app-my-card class="highlighted"> likhe */
}
💡Tip: :host zaroori hai kyunki DEFAULT se custom elements (<app-my-card>) "display: inline" jaisa behave karte hain — :host { display: block; } common pattern hai layout consistency ke liye.

::ng-deep child component ke andar CSS "penetrate" karne deta hai, encapsulation ko bypass karke — DEPRECATED hai (future Angular versions mein hat sakta hai), lekin abhi bhi common hai third-party components (jaise Material) style override karne ke liye.

/* Parent component CSS mein: */
::ng-deep .mat-button {
  background-color: purple;   /* Angular Material button ko override */
}
⚠️Common Mistake: ::ng-deep officially deprecated hai — modern alternative hai component ki apni styling API use karna (agar available ho), ya CSS custom properties (variables) jo cross-component boundary "leak" karne ke liye designed hain.