Angular View Encapsulation
The Component's decorator provides the encapsulation option which can be used to control how the encapsulation is applied on a per component basis.
We have three Types
- ViewEncapsulation.None
Angular does not apply any sort of view encapsulation meaning that any styles specified for the component are actually globally applied and can affect any HTML element present within the application. This mode is essentially the same as including the styles into the HTML itself.
@Component({
selector: 'app-no-encapsulation',
template: `
<h2>None</h2>
<div class="none-message">No encapsulation</div>
`,
styles: ['h2, .none-message { color: red; }'],
encapsulation: ViewEncapsulation.None,
})
export class NoEncapsulationComponent { }
- ViewEncapsulation.Emulated
Angular modifies the component's CSS selectors so that they are only applied to the component's view and do not affect other elements in the application (emulating Shadow DOM behavior).
@Component({
selector: 'app-emulated-encapsulation',
template: `
<h2>Emulated</h2>
<div class="emulated-message">Emulated encapsulation</div>
<app-no-encapsulation></app-no-encapsulation>
`,
styles: ['h2, .emulated-message { color: green; }'],
encapsulation: ViewEncapsulation.Emulated,
})
export class EmulatedEncapsulationComponent { }
- ViewEncapsulation.ShadowDom
Angular uses the browser's built-in Shadow DOM API to enclose the component's view inside a ShadowRoot (used as the component's host element) and apply the provided styles in an isolated manner.
@Component({
selector: 'app-shadow-dom-encapsulation',
template: `
<h2>ShadowDom</h2>
<div class="shadow-message">Shadow DOM encapsulation</div>
<app-emulated-encapsulation></app-emulated-encapsulation>
<app-no-encapsulation></app-no-encapsulation>
`,
styles: ['h2, .shadow-message { color: blue; }'],
encapsulation: ViewEncapsulation.ShadowDom,
})
export class ShadowDomEncapsulationComponent { }
Angular adds styles for this component only to the shadow DOM host, so they are not visible outside the shadow DOM.
Angular also adds the global styles from the NoEncapsulationComponent and EmulatedEncapsulationComponent to the shadow DOM host, so those styles are still available to the elements in the template of this component.