默认视图封装在 Angular 中是如何工作的 [英] How default view encapsulation works in Angular

查看:25
本文介绍了默认视图封装在 Angular 中是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,Angular 应用程序中组件的默认视图封装是 Emulated,即

As we know, default view encapsulation for a component in angular application is Emulated,ie

encapsulation: ViewEncapsulation.Emulated

如果不是 shadow dom,我真的不明白它在引擎盖后面是如何工作的.

I really do not understand how it works behind the hood if it is not a shadow dom.

推荐答案

angular 的三种封装方式

There are three types of encapsulation in angular

  • ViewEncapsulation.Emulated,这是默认设置
  • ViewEncapsulation.None
  • ViewEncapsulation.Native

假设您有两个不同的组件 comp-first 和 comp-second ,例如您在两者中定义

Assume that you have two different components comp-first and comp-second , For example you define in both of them

<代码>

一些段落

<p> Some paragraph </p>

所以如果你在 comp-first.css 中为段落应用一些样式

So if you apply some styling for paragraph in comp-first.css

p { 
   color: blue; 
 }

然后检查 comp-first.html 上的 p 元素并查找其样式会发现类似这样的内容

and then inspect p element on comp-first.html and look for its styling will find something like this

p[_ngcontent-ejo-1] {
  color: blue;
}

"_ngcontent-ejo-1" 只是一个简单的键,用于将此类元素与其他组件元素区分开来

"_ngcontent-ejo-1" is just a simple key for differentiate such an element from others components elements

如果你将此模式应用于这样的组件,例如 comp-first 然后你去检查任何元素,它不会为任何元素提供任何属性,如_ngcontent-ejo-1",因此应用任何样式或类将在全球范围内提供.

If you apply this mode to such a component for instance comp-first and then you go and inspect any element it will not provide any attribute like "_ngcontent-ejo-1" to any element , So applying any styling or class it will be provided globally .

这应该会产生与使用模拟模式相同的结果,但它在支持它的浏览器中带有 Shadow DOM 技术

This should give the same result as if you are using emulated mode but it comes with Shadow DOM technology in browsers which support it

这篇关于默认视图封装在 Angular 中是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆