在本文中,我们将了解什么是视图封装(view encapsulation)?它是如何工作的?Angular视图封装有哪些类型?什么是Shadow DOM?即使浏览器不支持Shadow DOM,Angular应用程序也支持样式范围吗?我们将一一详细地看到整个问题列表!
首先,让我向您解释用例,例如说我们有两个组成部分:
app.component // 1. parent component
demo.component // 2. child component
我们将在app组件内使用demo组件!现在,我们在两个组件上都具有一个h1选择器以显示title,由于视图封装与样式一起工作,我们在app组件中为选择器h1创建了样式。现在,当我们在app组件内部调用demo组件时,demo组件也有了一个h1选择器。然后发生了什么? 我们在app组件上创建的样式是否应该自动应用于demo组件的h1选择器?好吧,答案是否定的(实际上取决于您使用的是哪种ViewEncapsulation类型),Angular应用程序使用ViewEncapuslation模式进行仿真。那是什么?所以,本篇文章提供了有关ViewEncapsulation及其如何与Angular应用程序一起使用的所有答案。
在开始ViewEncapusaltion如何在Angular应用程序中工作之前,我们应该首先了解术语Shadow DOM。
Shadow DOM:
简单地说,Shadow DOM允许我们对元素应用作用域样式,而不影响其他元素。
ViewEncapsulation Types:
| mode | value | description |
|---|---|---|
| Emulated (default) | 0 | Emulate Native scoping of styles by adding an attribute containing surrogate id to the Host |
| Native | 1 | Use the native encapsulation mechanism of the renderer |
| None | 2 | Don't provide any template or style encapsulation |
| ShadowDom | 3 | Use Shadow DOM to encapsulate styles |
那么,现在我们学习一下ViewEncapsulation模式
1.ViewEncapsulation.None
如上所述,我创建了两个组件:
app.compontent.html
<h1>{{title}}</h1>
<hr>
<app-demo></app-demo>
app.component.ts
import { Component,ViewEncapsulation} from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation:ViewEncapsulation.None }) export class AppComponent { title = 'Hello from Parent'; }
app.component.css
h1{
background: blue;
text-transform: uppercase;
text-align: center;
}
在demo组件中,我们还使用h1选择器来显示title。当我们将ViewEncapsulation模式设置为None时,相同样式的父组件将分配给子组件。在下面找到demo组件。
demo.component.html
<h1>{{title}}</h1>
demo.component.ts
import { Component, OnInit } from '@angular/core';
@Component({ selector: 'app-demo', templateUrl: './demo1.component.html', styleUrls: ['./demo1.component.css'] }) export class Demo1Component implements OnInit { title = 'Hello from Child'; constructor() { } ngOnInit() { } }
Output:

2. ViewEncapsulation.Emulated
现在,如果我们将ViewEncapsulation模式更改为仿真模式,这是Angular应用程序默认提供的选项,输出将有所不同。尽管它不使用Shadow DOM,但仍可以将样式范围限定为特定元素。而且由于它没有使用Shadow DOM,因此它仍然可以在不支持Shadow DOM的浏览器中运行。以下是更新的 app.component.ts
import { Component,ViewEncapsulation} from '@angular/core';
@Component({ selector: 'jinal', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation:ViewEncapsulation.Emulated }) export class AppComponent { title = 'Hello from Parent'; }
我们刚刚更新了ViewEncapsulation模式,其余一切与之前的情况相同。

正如您所见到的,我们的组件和样式已被重写,并且为样式以及选择器添加了独特的ID类型,以在不使用Shadow DOM的情况下确定样式的范围。这不是一个好方法吗?
它已经为我们的样式分配了ID _ngcontent-c0,并且为我们的app.component的h1选择器分配了相同的ID,但是对于demo组件的h1选择器,它分配了不同的ID和_ngcontent–c1。
如果对您有帮助可以关注一下。文章会继续更新下去。