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
View Encapsulation 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
View Encapsulation 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
View Encapsulation Shadow DOM
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.