Behind the Scenes of View Encapsulation in Angular

Understand the working of View Encapsulation added to Angular components to protect styles leaking out and affecting other parts of the application.

In this article, let us understand how View Encapsulation works

What is Encapsulation

Encapsulation means bundling up data into a single unit hiding it from the outside world.

What is View Encapsulation

View Encapsulation is a mechanism that scopes styles of the component

Screenshot 2021-06-05 at 5.48.10 PM.png

View Encapsulation None

encapsulation: ViewEncapsulation.None

The styles defined in the component bleed out of the component and start affecting other components. All the styles of the component having encapsulation: ViewEncapsulation.None are added to the head of the html document which has the ability to affect styles in other component.

In the image below, notice the component having color : green style is affecting other component because of the encapsulation: ViewEncapsulation.None.

Screenshot 2021-06-05 at 8.18.09 PM.png

View Encapsulation Emulated

encapsulation: ViewEncapsulation.Emulated

With this, the styles are scoped to the component. This is the default value of encapsulation property provided by Angular. Angular add a unique attribute on the elements and generates the styles with the same attribute in the head of the document.

In the image below, notice the custom attribute attached to p tag in the <style> element.

Screenshot 2021-06-05 at 7.41.01 PM.png

View Encapsulation Shadow DOM

encapsulation: ViewEncapsulation.ShadowDom

Shadow DOM is a snapshot of actual DOM attached to the element.

The styles are scoped to the component and no elements are affected from the styles in the head. This works like Emulated but in this the styles are attached with the element in the DOM and not in the head of the document.

Screenshot 2021-06-05 at 8.17.36 PM.png

Thank you for reading.

I hope this has been helpful. Let me know your feedback in the comments. I would love to connect with you at Twitter | LinkedIn | GitHub

No Comments Yet