Understanding Angular’s ViewEncapsulation
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.
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…