View Encapsulation In Angular

Posted By : Gaurav Arora | 29-Sep-2018

Hi Guys, In this blog, we will be going to understand that, What is View Encapsulation in Angular.

View Encapsulation basically works on Shadow DOM, Shadow DOM allows you to attach hidden DOM trees to elements in a regular DOM tree - this shadow DOM tree starts with a shadow root, and the shadow root can be attached to any element you want, just like a normal DOM.

So, we can say that with the help of View Encapsulation we can define that styles defined in a particular component can affect the complete application on vice versa.

Angular has 3 built-in View Encapsulation Modes.

  • ViewEncapsulation.Emulated
  • ViewEncapsulation.Native
  • ViewEncapsulation.None
      import { Component, OnInit, ViewEncapsulation } from '@angular/core';

      @Component({
       selector: 'app-component',
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.css'],
       encapsulation: ViewEncapsulation.Emulated
      })
      
      export class AppComponent implements OnInit {
      
      }           
      

ViewEncapsulation.Emulated: This is our default Encapsulation mode in the angular app. In this mode, the styles defined in the component will stay in that component only and does not impact the entire app. Let’s say we are using Twitter Bootstrap, with this mode our component can still use the styles from the bootstrap library, but this is not with the case of native mode.

ViewEncapsulation.Native: In this mode, if we want that Angular use shadow dom then we can use ViewEncapsulation.Native. If we have defined ViewEncapsulation mode to native then we will lose all the global bootstrap styles.

ViewEncapsulation.None: If we don’t want to use any Encapsulation in the app, then we can use ViewEncapsulation.None, what this will do is, this will apply the styles in the complete app, which is defined in it’s a particular component. Like we have a defined a class with the name of the banner, even it is defined in any other component it will not pick that component’s class. It will use the style defined in the component with ViewEncapsulation.none.

About Author

Author Image
Gaurav Arora

Gaurav is an experienced UI developer with experience and capabilities to build compelling UI's for Web and Mobile Applications.

Request for Proposal

Name is required

Comment is required

Sending message..