Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How default view encapsulation works in Angular

As we know, default view encapsulation for a component in angular application is Emulated,ie

encapsulation: ViewEncapsulation.Emulated

I really do not understand how it works behind the hood if it is not a shadow dom.

like image 445
Ashutosh Ranjan Jha Avatar asked Oct 25 '25 04:10

Ashutosh Ranjan Jha


2 Answers

There are three types of encapsulation in angular

  • ViewEncapsulation.Emulated and this is set by default
  • ViewEncapsulation.None
  • ViewEncapsulation.Native

Emulated mode

Assume that you have two different components comp-first and comp-second , For example you define in both of them

<p> Some paragraph </p>

So if you apply some styling for paragraph in comp-first.css

p { 
   color: blue; 
 }

and then inspect p element on comp-first.html and look for its styling will find something like this

p[_ngcontent-ejo-1] {
  color: blue;
}

"_ngcontent-ejo-1" is just a simple key for differentiate such an element from others components elements

None mode

If you apply this mode to such a component for instance comp-first and then you go and inspect any element it will not provide any attribute like "_ngcontent-ejo-1" to any element , So applying any styling or class it will be provided globally .

Native mode

This should give the same result as if you are using emulated mode but it comes with Shadow DOM technology in browsers which support it

like image 73
Abdulrahman Falyoun Avatar answered Oct 27 '25 17:10

Abdulrahman Falyoun


When you write

<div class="XXX"></div>

With the style

XXX { color: red; }

The compiler will translate it to

<div class="XXX" ng_host_c22></div>

With the style

XXX[ng_host_c22] { color: red; }

it simply adds an unique (randomly generated) attribute to your elements and style, to avoid them colluding with other styles.

This means if you declare the class XXX in 2 different components, then they will have a different attribute, and not collude.