Assuming that you are aware of Shadow DOM. If not, I encourage you to have a quick look at Shadow DOM and MDN.
Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree .
In Angular, whilst you create the component you set a few properties, a.k.a. metadata, in the decorator. One of the properties from it called
encapsulation which we are going to discuss in the article.
The angular component comprises of the template, style, and logic. Each component style is appended to the
head of the document (default) which is, of course, scoped. There are mainly two types of encapsulations offered by Angular.
- Native: Uses browser’s native deprecated version of Shadow DOM. Check for browser support before enabling it.
- ShadowDom: Uses browser’s native Shadow DOM v1 for better cross-browser support and is a shared standard across the browsers. Check the difference between Shadow DOM v0 to v1.
- Emulated: Imitates behavior of Shadow DOM to scope the CSS for component and appends to the
- None: Neither Shadow DOM nor custom implementation, it is just like global CSS which gets appended to the
head.It’s not the type rather disabling Shadow DOM or Custom Shadow DOM behavior.
ViewEncapsulation.Emulated as default
encapsualtion mode. For instance, there is
company-list component with some styles in it given beneath:
Now, let’s try with all possible options for encapsulation and check how DOM/Shadow DOM for the component is generated along with style scoped or not, respectively.
If you check compiled CSS and HTML it is under
#shadow-root and it is Shadow DOM which is scoped within the component itself. It simply means this component will not harm any other styles and it remains unaffected from other styles as well.
Note: ViewEncapsulation.ShadowDom = Shadow DOM v1 while ViewEncapsulation.Native = Shadow DOM v0 (deprecated version)
Well, things went differently here, isn’t it! What just happened with class from
.list to .list[_ngcontent-c1] and then
_ngcontent-c1, etc. Angular is imitating encapsulated styles where
_nghost-c* is root element,
_ngcontent-c* are contents of the root element, and
-c*attribute selector for CSS followed by a key to maintain uniqueness. This will create scoped CSS for a component without using Shadow DOM.
This is pretty straightforward. We can just ask Angular not to implement any encapsulation; neither
Emulated. As you see, styles are appended in
head globally it will be applied to other components as well since there is nothing like the scope.
Worth reading it! Then start clapping 👏 :D so more people can see this… :)