To understand ViewEncapsulation in Angular, first we should understand about Shadow DOM. You can learn in detail about Shadow DOM here. Putting it in simple words, Shadow DOM brings Encapsulation in HTML Elements. Using the Shadow DOM , markup, styles, and behaviors are scoped to the element and do not clash with other nodes of the DOM. Shadow DOM is part of Web Components, which encapsulates styles and login of element.
Angular Components are made up of three things:
- Component class
Combination of these three makes an Angular component reusable across application. Theoretically, when you create a component, in some way you create a web component (Theoretically, Angular Components are not web components) to take advantage of Shadow DOM. You can also use Angular with browsers, which does not support Shadow DOM because Angular has its own emulation and it can emulate Shadow DOM.
To emulate Shadow DOM and encapsulate styles, Angular provides there types of ViewEncapsulation. They are as follows:
Let us try to understand it using an example. I have created a component, as shown below:
We are setting the style of h1 in the component CSS. We have also created another component:
In AppChildComponent, we are also using h1 tag. To understand different ViewEncapsulation options, we will change the metadata of AppComponent.
Let us start with ViewEncapsulation.None, in this option,
- There is no shadow DOM
- Style is not scoped to component
As you run the application, you will find h1 style has applied to both components, even though we set style only in AppComponent. It happened because in AppComponent we have set encapsulation property to ViewEncapsulation.None.
In the browser when you examine source code, you will find h1 style has been declared in the head section of the DOM.
Therefore, in ViewEncapsulation.None, style gets move to the DOM head section and is not scoped to the component. There is no Shadow DOM for the component and component style can affect all nodes of the DOM.
Next, let us explore ViewEncapsulation.Native, in this option:
- Angular will create Shadow DOM for the component.
- Style is scoped to component
As you run the application, you will find h1 style has applied to both components, even though we set style only in AppComponent. It happened because in AppComponent we have set encapsulation property to ViewEncapsulation.Native, and we are using AppChildComponnet as child inside template of AppComponent.