In your Angular components you’re able to specify a component’s ViewEncapsulation. It defines template and style encapsulation options available for components, and thus specifies the strategy on how styles are applied to a component. By default, styles are appended to the document’s <head> and is encapsulation emulated, but there are other options as well.

Shadow DOM

Before we can get into the ViewEncapsulation options, we first have to know about the Shadow DOM. In an HTML document all styles and elements are in one global scope and can be accessed through a querySelector . The selector will always find the object, no matter where or how deep the element is nested in the DOM. This also applies to the CSS selectors. While there are advantages to this behaviour, for example, a single CSS class can style everything it applies to immediately, there are also situations where you want elements to be encapsulated from the rest of the DOM.

iframe example from w3schools.com

A popular and easy to understand example are <iframe> elements, which encapsulate a document. They are designed to embed a full document within HTML. You don’t want your iframe to be affected by the global styling of your parent document. Iframes are not using the Shadow DOM though, since its DOM elements are in a completely separate context, but you’re still basically creating “a DOM within a DOM”, which is comparable to what the Shadow DOM does. This notion is not a new concept, but has only recently been opened for use by web developers. Browsers have internally used it for a longer time to create complex components. For example, the input range selector looks like this under the hood in Chrome:

<input type=”range”>

Shadow DOM was introduced to address DOM tree encapsulation problems. So how does Angular leverage the Shadow DOM? An Angular application consists out of components with their own template and styles. When creating a component, Angular can render this component in a shadowRoot. This shadowRoot is the Shadow DOM for that component, and gives us encapsulation for the component out of the box. Easy enough, right?

There is a small problem however. The Shadow DOM isn’t supported by all browsers yet. So where does that leave us?

Screenshot from https://caniuse.com