View.Encapsulation

B. Chepkorir
SD Tidbits
Published in
3 min readJul 28, 2022
Photo by Edward Jenner

In a bid to try and demystify the Shadow DOM in the Angular context. Here we go.

The Shadow DOM is a fundamental part of web elements and components. In fact some ubiquitous elements, like the Input element, have Shadow DOMs we cannot readily access from browser inspects or with JavaScript.

Why should we care? The Light DOM works fine as is.

It can be a great strategy to use with modularity. Especially, when managing styles or themes for multiple integrated components or applications. For example, in Single-Page Applications (SPAs) or Micro Frontends.

What does encapsulation look like?

Angular abstracts away some Shadow DOM API complexities so apps can use different modes seamlessly.

Within a component’s decorator, just add the encapsulation property and set it to a relevant mode like ViewEncapsulation.ShadowDom.

There are 3 modes: ShadowDom, Emulated, & None.

Todos on codesandbox.io

In this application, the list of to-dos are <p> elements. They exist within their own to-dos component that is being pulled into the root component.

The statement “Track your list of to-dos.” is a <p> element that is directly in the root component.

The color, red, is a style for <p> elements and is defined in the to-dos component. Only.

When we switch encapsulation modes, we get a similar experience when using Emulated and ShadowDom:

  • The <p> elements within the to-dos component are colored red.
  • The <p> element directly in the root component is NOT.

This is because the red-color style is isolated from the root <p> element.

Why?

With Emulated encapsulation, Angular decorates the to-dos component’s elements with unique attributes. These attributes specifically identify those elements for the component in the Light DOM. So, the component’s own styles apply to just the component’s own elements.

With ShadowDom encapsulation, all the component’s elements are put in the Shadow DOM. So, the component’s styles DO NOT exist in the Light DOM — where the root <p> element is.

How does this strategy help micro frontends?

Imagine a scenario where applications built by different teams share a common header, footer, or navigation sidebar. Essentially, one home and look.

Components and elements styling could differ from app to app. With a high risk of unintended modification where they mix or match. Encapsulating can help set some modification boundaries. Especially, when the shadow roots are closed.

Note:

The shadow roots created by Angular are usually open — this means they can be inspected and modified.

With None encapsulation mode, all the <p> elements in the application are colored red.

--

--

B. Chepkorir
SD Tidbits

Software Development Enthusiast | Writer on Code Like A Girl & FreeCodeCamp -- I "talk" fast