在本文中,咱们将了解什么是视图封装(view encapsulation)?它是如何工做的?Angular
视图封装有哪些类型?什么是Shadow DOM
?即便浏览器不支持Shadow DOM
,Angular
应用程序也支持样式范围吗?咱们将一一详细地看到整个问题列表!css
首先,让我向您解释用例,例如说咱们有两个组成部分:html
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
。markdown
简单地说,Shadow DOM容许咱们对元素应用做用域样式,而不影响其余元素。app
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模式oop
如上所述,我建立了两个组件:学习
app.compontent.htmlspa
<h1>{{title}}</h1>
<hr>
<app-demo></app-demo>
复制代码
app.component.tscode
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() { } }
如今,若是咱们将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
。
若是对您有帮助能够关注一下。文章会继续更新下去。