View Encapsulation 控制组件的 CSS 如何被限定作用域——默认情况下,Angular 隔离每个组件的样式,以便它们不会泄漏到其他组件或受其他组件影响。这解决了 CSS 的全局作用域问题。
默认值:Emulated 封装
ts
({
: ,
: ,
: [],
})
{}
使用默认的 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 强制样式穿透到子元素(功能强大但不推荐使用——它会破坏封装)。
View Encapsulation 使 Angular 组件可以安全地独立设置样式——你可以在一个组件中写 h2 { color: blue },而无需担心破坏应用中所有的 <h2>。
理解默认的 Emulated 模式(以及 None/ShadowDom 替代方案,加上用于有意例外的 :host 和 ::ng-deep)对于在大型应用中管理样式以及构建组件库(样式泄漏会是一个严重问题)很重要。