When and why should we use View Encapsulation in angular

Codecraft.TV has an amazing article on ViewEncapsulation that you can refer to get a better understanding.

To just summarize it:

ViewEncapsulation.Emulated: Angular changes our generic css class selector to one that target just a single component type by using automatically generated attributes.

Any styles we define on a component don’t leak out to the rest of the application but with ViewEncapsulation.Emulated our component still inherits global styles.


ViewEncapsulation.Native: If we want Angular to use the shadow DOM we can set the encapsulation parameter to use ViewEncapsulation.Native

With ViewEncapsulation.Native styles we set on a component do not leak outside of the components scope.

This is great if we are defining a 3rd party component which we want people to use in isolation. We can describe the look for our component using css styles without any fear that our styles are going to leak out and affect the rest of the application.

However with ViewEncapsulation.Native our component is also isolated from the global styles we’ve defined for our application. So we don’t inherit the global styles and have to define all the required styles on our component decorator.

Finally ViewEncapsulation.Native requires a feature called the shadow DOM which is not supported by all browsers.


ViewEncapsulation.None: If we don’t want to have any encapsulation at all, we can use ViewEncapsulation.None.

If we don't encapsulate anything, the style we defined in the component will leak out and started affecting the other components.

Some other resources that you might want to have a look into:

  1. VIEW ENCAPSULATION IN ANGULAR - By Thoughtram
  2. View Encapsulation by Rangle.IO
  3. Scoping Your Styles in Angular With ViewEncapsulationView
  4. Diff between ViewEncapsulation.Native, ViewEncapsulation.None and ViewEncapsulation.Emulated

Tags:

Css

Angular