Skip to main content

11. View Encapsulation Strategies in Angular

Angular provides several view encapsulation strategies that control how styles are applied to components. Here’s a brief overview of the different strategies:

1. Emulated (Default)

  • Description: This is the default strategy used by Angular. Styles defined in a component are scoped to that component only, simulating Shadow DOM behavior.
  • How It Works: Angular adds unique attributes to elements and styles, allowing styles to apply only to elements of the component without affecting the global styles or other components.
  • Use Case: Ideal for most scenarios where you want encapsulation without relying on browser support for Shadow DOM.

2. None

  • Description: Styles are applied globally, affecting the entire application, not just the component.
  • How It Works: The styles are added to the global stylesheets, so they can affect any element within the application.
  • Use Case: Use this strategy when you need styles to be shared across multiple components or for styling libraries that require global styles.

3. Shadow DOM

  • Description: This strategy uses the native Shadow DOM of the browser to encapsulate styles.
  • How It Works: Styles defined in the component are encapsulated within the Shadow DOM, preventing them from affecting or being affected by styles outside the component.
  • Use Case: Use this strategy if you need true style encapsulation and your application targets browsers that support Shadow DOM.

Summary Table

StrategyDescriptionUse Case
EmulatedStyles scoped to the component (default)Most scenarios needing encapsulation
NoneStyles applied globallyShared styles or styling libraries
Shadow DOMUses native Shadow DOM for encapsulationTrue encapsulation with browser support

Example Usage

You can set the encapsulation strategy in your component using the encapsulation property:

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

@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
encapsulation: ViewEncapsulation.Emulated // Change to None or ShadowDom as needed
})
export class ExampleComponent {}