有人能解释一下ViewEncapsulation.None和ViewEncapsulation.Emulated与ViewEncapsulation.Native在angular2中的区别吗?
我试着在谷歌上搜索并阅读一些文章,但我无法理解其中的区别。
下面有两个组件Home (home.ts),即父组件和MyComp (mycomp.ts)。我希望在子组件中使用的父组件中定义样式。
我应该使用ViewEncapsulation.Native还是ViewEncapsulation.None?
home.ts
import {Component, ViewEncapsulation} from 'angular2/core';
import {MyComp} from './my-comp';
@Component({
selector: 'home', // <home></home>
providers: [
],
directives: [
MyComp
],
styles: [`
.parent-comp-width {
height: 300px;
width: 300px;
border: 1px solid black;
}
`],
template:`
<my-comp></my-comp>
<div class="parent-comp-width"></div>
`,
encapsulation: ViewEncapsulation.Native
})
export class Home {
}my-comp.ts
import {Component} from 'angular2/core';
@Component({
selector: 'my-comp', // <home></home>
template: `
<div class="parent-comp-width">my-comp</div>
`
})
export class MyComp {
}发布于 2016-02-26 12:45:03
update如果希望将添加到Parent中的样式应用于Child,则需要在Child组件中设置ViewEncapsulation.None,这样就不会阻止样式溢出。
Emulated和Native只是两种不同的方法,可以防止样式从组件中流入或流出。None是唯一允许样式跨越组件边界的。
原始
ViewEncapsulation.Emulated很相似,但是聚合填充更昂贵,因为它们填充了很多浏览器API,即使大多数API从未被使用过。Angulars Emulated仿真只是增加了它所使用的成本,因此对于角度应用来说效率要高得多。发布于 2018-08-30 12:56:14
角使用ViewEncapsulation.Emulated作为默认的封闭模式。
发布于 2019-05-28 06:22:35
ViewEncapsulation值:
... <style> div[\_ngcontent-c0] { background-color: lightcoral; } </style> ...
选择器已被修改,以便将div元素与名为_ngcontent-c0的属性匹配,尽管您可能会在浏览器中看到不同的名称,因为属性的名称是由角动态生成的。
为了确保样式元素中的CSS只影响由组件管理的HTML元素,模板中的元素将被修改,以便它们具有相同的动态生成属性,如下所示:
...
<div _ngcontent-c0="" class="form-group">
<label _ngcontent-c0="">Name</label>
<input _ngcontent-c0="" class="form-control ng-untouched ng-pristineng-invalid"
ng-reflect-name="name" name="name">
</div>
...应谨慎使用本机值和无值。浏览器对阴影DOM特性的支持是如此有限,因此只有在使用为其他浏览器提供兼容性的polyfill库时,使用本机选项才是合理的。
None选项将由组件定义的所有样式添加到HTML文档的head部分,并让浏览器知道如何应用它们。这可以在所有浏览器中工作,但是结果是不可预测的,并且不同组件定义的样式之间不存在隔离。
https://stackoverflow.com/questions/35651993
复制相似问题