Blog

  • View Encapsulation In Angular

    Posted by Gaurav Arora | Last Updated: 14-Jan-19

    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.

Tags: Angular2