View Encapsulation は、コンポーネントの CSS スコープがどのように設定されるかを制御します。デフォルトでは、Angular は 各コンポーネントのスタイルを分離 して、他のコンポーネントに漏れたり、他のコンポーネントから影響を受けたりしないようにします。これは CSS のグローバルスコープの問題を解決します。
デフォルト: Emulated encapsulation
({
: ,
: ,
: [],
})
{}
デフォルトの Emulated モードでは、その h2 { color: blue } は他のコンポーネントの <h2> に影響を与えず、外部スタイルもこのコンポーネントに入り込みません。
<!-- Angular adds unique attributes to scope the styles -->
<app-card _nghost-abc>
<h2 _ngcontent-abc>Title</h2>
</app-card>
<style>h2[_ngcontent-abc] { color: blue; }</style> <!-- scoped by attribute -->
Angular は自動的に一意の _ngcontent/_nghost 属性をコンポーネントの要素に追加し、CSS セレクターを書き直して、それらのみにマッチするようにします。これはネイティブ Shadow DOM を使用せずに、スコープされたスタイルをエミュレートしています。
ViewEncapsulation.Emulated (default) → scoped via added attributes (works everywhere)
ViewEncapsulation.ShadowDom → real browser Shadow DOM (true isolation)
ViewEncapsulation.None → NO scoping — styles are global (leak everywhere)
/* style a child component's internals from the parent */
:host { display: block; } /* the component's own host element */
:host(.active) { ... } /* host with a class */
::ng-deep .child-class { color: red; } /* pierce into children (use sparingly — deprecated-ish) */
:host はコンポーネント自身のルート要素をスタイルします。::ng-deep はスタイルを子孫に強制的に適用します(強力ですが非推奨 — encapsulation を破壊します)。
View Encapsulation により、Angular コンポーネントは 隔離された状態でスタイルを設定しても安全 です。アプリケーション内のすべての <h2> を上書きする心配をせずに、1 つのコンポーネントで h2 { color: blue } を記述できます。
デフォルトの Emulated モード(および None/ShadowDom の代替案、さらに意図的な例外のための :host と ::ng-deep)を理解することは、大規模アプリケーションでのスタイル管理、およびスタイルの漏れが深刻な問題となるコンポーネントライブラリの構築に重要です。