View Encapsulation
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] { ... }- Emulated (default) = fake scoping, unique attributes se
- None = global styles, koi isolation nahi
- ShadowDom = true browser-level isolation
: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 */
}::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 */
}