Native和ShadowDom ViewEncapsulation有什么区别?

时间:2018-11-21 10:23:32

标签: angular shadow-dom angular7

在我当前的angular 7应用程序中,我们正在努力处理库中的组件,这需要一些CSS资源。我们不希望将这些资源应用于所有其余的应用程序,而是应用于一个特定的组件,即其子孙。

在研究过程中,我们发现了以下两个有趣的选择:

encapsulation: ViewEncapsulation.Native

和:

encapsulation: ViewEncapsulation.ShadowDom

结果,他们俩似乎都使用了浏览器的影子dom实现。

这些选项之间有什么区别?

2 个答案:

答案 0 :(得分:3)

几天前,这一直困扰着我,然后我意识到,他们融合了一点,但并没有完全融合。实际上,两者之间的差异在于 the newer version of shadowDOM (v1) 。正如您在angular的代码源中看到的 here 一样,他们为 array(1) { [0]=> string(19) "field_5bf5205ca3910" } Array Argomenti (this is a name and link) array(1) { [0]=> string(19) "field_5bf5205ca3910" } Array Cammini (this is a name and link) array(1) { [0]=> string(19) "field_5bf5205ca3910" } Array La mia casa (this is a name and link) 添加了另一个条件:

  

在这里,他们共享相同的返回

ViewEncapsulation.ShadowDom
  

然后他们检查是否为 ViewEncapsulation.ShadowDom (其他条件)

 case ViewEncapsulation.Native:
 case ViewEncapsulation.ShadowDom:
      return new ShadowDomRenderer(this.eventManager, this.sharedStylesHost, element, type);    

因此, if (component.encapsulation === ViewEncapsulation.ShadowDom) { this.shadowRoot = (hostEl as any).attachShadow({mode: 'open'}); } else { this.shadowRoot = (hostEl as any).createShadowRoot(); } 是向 ShadowDOM V1 添加支持的步骤,并且也许弃用 { {1}} ,如 here:

所述
  

ViewEncapsulation.Shadow作为新API添加,而不是更改ViewEncapsulation.Native选项的行为,这可能会导致   对于当前使用v0 API的开发人员而言,会产生意想不到的结果。这个   应该(最终?)不赞成使用ViewEncapsulation.Native选项。

答案 1 :(得分:0)

Angular使用ViewEncapsulation将样式和视图限制为已提及的组件,我想您已经知道这一点。 本机没有很多细节,我知道的是它对浏览器是有选择性的,并不是所有的浏览器实际上都认可它。 对于ShadowDom,Angular文档有一个解释,但并不太详细,尽管此摘录清除了一些部分:“请注意,影子DOM绝不是什么新鲜事物,浏览器已经使用了很长时间来封装内部结构了。以一个元素为例,以一个元素为例,其中显示了默认的浏览器控件。您在DOM中看到的只是该元素,但它的影子DOM中包含一系列按钮和其他控件。这样您就可以实际操作自己的自定义元素的影子DOM。” 在此处查看更多信息:MDN Docs