What is View Encapsulation in Angular ?

Pravin M
2 min readNov 28, 2023
What is View Encapsulation in Angular

Source: What is View Encapsulation in Angular ?

For more questions and answers visit our website at Frontend Interview Questions

In Angular, ViewEncapsulation is a feature that controls the way styles are applied and scoped to components. It is a mechanism that encapsulates the styles defined in a component to prevent them from affecting other components in the application.

By default, Angular uses the ViewEncapsulation.Emulated mode, also known as the “shadow DOM” emulation. In this mode, Angular emulates the behavior of the shadow DOM by adding a unique attribute to the component’s HTML elements and applying styles with these attributes. This way, styles defined in a component only affect the elements within that component’s template and do not leak out to other parts of the application.

There are three ViewEncapsulation modes available in Angular:

  1. ViewEncapsulation.Emulated (default): This mode emulates the shadow DOM by adding unique attributes to the component’s elements. The styles defined within the component’s template are scoped to that component only. ViewEncapsulation.Emulated will add the css style in the head section of your website and reference your component’s unique id(_ngcontent) to apply it.
  2. ViewEncapsulation.None: In this mode, styles defined in a component’s template are not encapsulated and can affect the entire application. It’s important to use this mode with caution, as it can lead to style collisions and unintended side effects when multiple components use the same styles.
  3. ViewEncapsulation.ShadowDom: This mode uses the native browser’s shadow DOM implementation to encapsulate the styles. It requires the browser to support the shadow DOM. With this mode, the component’s styles are truly isolated within the component and do not leak out to other components or the global styles. ViewEncapsulation.ShadowDom will add the css style inside the generated DOM of your component.

To specify the ViewEncapsulation mode for a component, you can use the `encapsulation` property in the component’s metadata:

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

@Component({
selector: ‘app-my-component’,
templateUrl: ‘./my-component.component.html’,
styleUrls: [‘./my-component.component.css’],
encapsulation: ViewEncapsulation.Emulated // or ViewEncapsulation.None or ViewEncapsulation.ShadowDom
})
export class MyComponent {
// Component logic goes here
}

Conclusion:

By understanding and utilizing ViewEncapsulation in Angular, you can have better control over styles and prevent unintended style interference between components in your application.

--

--

Pravin M

I am a frontend developer with 10+ years of experience