angular ViewEncapsulation
2021-03-03 本文已影响0人
云上笔记
ViewEncapsulation 用于定义组件的样式封装选项,当你新建了一个组件时,可以通过配置这个选项来设置该组件的样式如何生效
ViewEncapsulation 的三个可选值
Emulate
:可进不出,默认项,公共样式可作用于该组件,但该组件样式不会影响其他组件;
None
:可进可出,当前组件的样式作用于全局,会影响其他组件样式;
ShadowDom
:不进不出,使用shadowDom封装样式,公共样式不能作用于该组件,该组件的样式也不会影响其他组件,可以把它看成一个独立的html;
ViewEncapsulation.None 的用法
// ShadowNoteComponent
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-shadow-note',
template: `
<p class="title">
ShadowNoteComponent ==> ViewEncapsulation.None
</p>
`,
styles: [`
.title{
color: skyblue;
font-size: 18px;
font-weight: bold;
}
`],
encapsulation: ViewEncapsulation.None
})
// AppComponent
@Component({
selector: 'app-root',
template: `
<p class="title">AppComponent ==> ViewEncapsulation.Emulate</p>
<app-shadow-note></app-shadow-note>
`,
styles: [`
.title{
color: red;
font-size: 14px;
}
`],
})
最后的效果如下
图片.png
可以看到,AppComponent 的p
标签上出现了两个 title 样式,分别是 AppComponent、 ShadowNoteComponent 组件中定义的,由于 ShadowNoteComponent 组件设置了ViewEncapsulation.None,使得该组件内样式作用于全局,同时,angular 为 AppComponent 中的 title 样式创建了一个 [_ngcontent-qda-c0] 选择器,其样式权重大于另一个 .title,最终表现为红色14号粗体。
个人感觉 ViewEncapsulation.None 最好慎用