In this article, we will see what actually view encapsulation is? How it is working? What are the types of view encapsulation available in angular? What is Shadow DOM? Does angular application support the scope for styling, even though the browser doesn’t support shadow DOM? We will see this entire list of questions in details one by one!
So to start with, let me explain you the use case, say for example we had two components
- app.component ( parent component)
- demo.component( child component)
We will be using the demo component inside the app component, all right! Now furthermore we had an h1 selector on both the components to display title, and as view encapsulation works with styling, we had created a style in app component for the selector h1. Now as we are calling the demo component inside the app component and demo component also had an h1 selector. What happened then? Does that style which we created on app component should automatically be applied to the demo component’s h1 selector? Well, the answer is NO(Actually depends on which ViewEncapsulation Type you are using), Angular application by default uses ViewEncapuslation mode to emulate. Now, what ’s that? So this article has all the answers for the ViewEncapsulation and how it is working with the angular application.
Before starting with ViewEncapusaltion works in Angular application we should know about the term Shadow DOM first.
Shadow DOM
In a simple word, Shadow DOM will allow us to apply Scoped Styles to elements without affecting other elements.
ViewEncapsulation Types
| Mode | Value | Description |
| Emulated (Default) | 0 | No shadow DOM but provide style encapsulation by adding new host element attribute to all selectors. |
| None | 2 | No shadow DOM. |
| ShadowDom | 3 | Uses Shadow DOM for style encapsulation. |
Okay so now let’s see all the ViewEncapsulation Mode in details one by one.
ViewEncapsulation.None
So as discussed above use case, I had created two components as shown below,
app.component.html
- <h1> {{title}} </h1>
- <hr>
- <app-demo></app-demo>
app.component.ts
- import { Component,ViewEncapsulation} from '@angular/core';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css'],
- encapsulation:ViewEncapsulation.None
- })
- export class AppComponent {
- title = 'Hello from Parent';
- }

Amit Kumar SinghPosted Mar 11, 2019, 7:29 AM
Thanks for Sharing !!!