View Encapsulation in Angular (emulated, none, shadowDom )
Angular provides flexibility to control how styles are applied to components. Using this properly we can define the scope of styles.
It determines whether the styles defined in a component affect only that component or can affect other components as well.
Angular provides three modes of view encapsulation:
we mention like this in our component:
- ViewEncapsulation.Emulated (default )
- ViewEncapsulation.None
- ViewEncapsulation.ShadowDom
We will create two component: comp1 and comp2, then we will understand all three property one by one.
ViewEncapsulation.emulated ( default )
- Angular creates scoped styles by adding unique attributes to the component’s elements.
- This ensures that styles apply only to that component.
Example:
// comp1 html file
<h2 class="box">comp1 works!</h2>
// comp1 ts file
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.scss'],
encapsulation: ViewEncapsulation.Emulated
})
export class Comp1Component {
}
// comp2 html file
<h2 class="box">comp2 works!</h2>
// comp2 ts file
import { Component } from '@angular/core';
@Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.scss']
})
export class Comp2Component {
}
// app component html file
<app-comp1></app-comp1>
<app-comp2></app-comp2>
We can see here one class has been added prefix with ng, that makes it unique and scoped with comp1 only.
ViewEncapsulation.None
- No encapsulation happens if we use None.
- styles are global and can affect other components.
- In the same above example, I am adding None and showing you the screenshot. No extra class has been added.
- Style of box class will be applicable in project level, where ever box class is used in other component, style of box class will be applied automatically.
ViewEncapsulation.ShadowDom
- Offers the strongest isolation but has limited browser support, only available in modern browsers.
- Uses the browser’s native Shadow DOM API to encapsulate styles within a component’s view.
- Completely isolated; no styles from outside the Shadow DOM can affect the component, and styles defined in the component will not affect anything outside it.
We will take same example by replacing ViewEncapsulation.ShadowDom
in comp1 and it creates one shadow-root and inside that it create some styles tag, and it picks style from there.
lets see in this screenshot:
Please comment for related discussion, I will be happy to discuss it.
I created a GitHub repository for angular practice, You are welcome to contribute your learning in this repository.
https://github.com/bittu1040/Angular-Practice/tree/master/src/app/view-encapsulation
Thanks for reading till here, You can follow me if you like this article and learnt something new.
You can find me here for any further discussion: