View Encapsulation
Encapsulation is the concept of bundling similar blocks of code together as one unit. In this article, I talk about view encapsulation.
View encapsulation defines how styles in components in Angular remain in the host element without affecting the rest of the application unless explicitly allowed to. In other words, the styles in the component are bundled together and restricted to the component and its linked style url(s).
The option is added in the @Component decorator. It is also imported from @angular/core
There are three options provided for view encapsulation in the decorator of an angular component.
This is the default option. With this option all styles specified in the component remain within the boundaries of the component. From the name, the emulated option emulates this behavior from the shadow DOM by adding attributes to only the css/scss selectors within the component that are used for the template of the component.
2. ShadowDom
领英推荐
Shadow DOM is a hidden DOM tree created by modern browsers to hold elements that are rendered but are not included in the main DOM. Shadow DOM is the baseline of encapsulation as code within the shadow DOM is not meant to affect the main DOM tree.
As an option in view encapsulation in Angular, it creates a shadow root in the components’ host element. The shadow DOM is the ability of modern browsers to create ‘boundaries’ that separate the subtree of DOM elements from the main DOM elements. The shadow DOM keeps the markup structure of style and behavior from the main application.
3. None
This option removes any boundaries between the component and the main DOM tree. The styles used in the main DOM tree directly affect the template file styles and vice versa. The styles can propagate from the template to the rest of the application and can easily lead to ‘CSS leakage’.
The emulated/ default option usually comes with additional attributes on the elements.
The first is _nghost which is an attribute added to parent view component or tag while the other one is __ngcontent is on the child components/tags
The host has an attached attribute value that serves as its id in the shadow DOM and all its children will have the same id.
Data Ninja @ RSM Eastern Africa LLP || Data Analyst || Python, SQL, PowerBI, Excel, Tableau
2 年Great