View Encapsulation in Angular

Angular by default makes sure that the style that we write in a component will be applied only to the elements of the component. angular enforces this style encapsulation by giving the same attribute to all elements in a component. angular does this for each component by adding a different unique attribute name for each component.

Basically angular tries to emulate the shadow DOM, the shadow DOM is a technology not supported by all browsers where each element has its own kind of shadow DOM behind it, where you then could assign styles to each element without affecting other elements in the DOM.

Since this technologie is not supported by all browsers, angular emulates this behaviour by adding a unique attribute to all elements in the component and specifying the css style to that attribute.

we can override the default encapsulation by adding a property named “encapsulation” to the object passed to the @component decorator. The value for the property will define the mode for the view encapsulation and here are 3 modes we can use: ShadowDom/Native, None and Emulated.

  • Emulated – is the default behaviour, it emulates the shadow DOM like I described above.
  • None – disable the view encapsulation, the styles in the component will affect globally.
  • ShadowDom – uses the shasowDom technologie. it will give the same result as emulated, but only in browsers which support it.

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

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None

export class AppComponent  {}