View Encapsulation

Overview

View encapsulation is a crucial concept in Angular that ensures the isolation of styles and templates within components, preventing unintended style conflicts and providing a structured approach to managing the appearance of your application. In this chapter, we will dive into the world of view encapsulation, exploring its types, how to use them, and providing practical examples to solidify your understanding.

Understanding View Encapsulation

View encapsulation in Angular ensures that the styles define in one component do not effect other components. It provides a way of scope the styles and templates of a component, making your application more maintainable and less prone to styling issues.

Types of View Encapsulation

Basically there are three options for view encapsulation provided by the angular to be used in component decorator:

Emulated View Encapsulation (Default)

Emulated view encapsulation is the default mode in Angular. It emulates the behavior of the Shadow DOM by adding a unique attribute to the elements of a component. This attribute acts as a style scoping mechanism, preventing styles from leaking out and affecting other parts of the application. Let's see it in action:

import { Component } from '@angular/core';

@Component({
 selector: 'app-emulated-example',
 template: '<p >Emulated View Encapsulation</p>',
 styles: ['.my-style { color: red; }']
})
export class EmulatedExampleComponent { }

In this example, the styles define within the component are scoped to the unique attribute added to the paragraph element.

Shadow DOM View Encapsulation

Shadow DOM view encapsulation used the native Shadow DOM provided by the browser to create isolated components. Styles are encapsulated within the Shadow DOM, providing true style isolation. To use Shadow DOM view encapsulation, you set the encapsulation option to ViewEncapsulation.ShadowDom when defining a component:

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
 selector: 'app-shadow-dom-example',
 template: '<p >Shadow DOM View Encapsulation</p>',
 styles: ['.my-style { color: blue; }'],
 encapsulation: ViewEncapsulation.ShadowDom
})
export class ShadowDomExampleComponent { }

None View Encapsulation

In cases where you want to disable view encapsulation altogether, you can use the ViewEncapsulation.None mode. This approach is generally discouraged, as it removes all encapsulation, potentially causing style conflicts and making it challenging to maintain your application's styles.

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
 selector: 'app-none-example',
 template: '<p >No View Encapsulation</p>',
 styles: ['.my-style { font-weight: bold; }'],
 encapsulation: ViewEncapsulation.None
})
export class NoneExampleComponent { }