Search code examples
angularshadow-domangular7

What is the difference between Native and ShadowDom ViewEncapsulation?


In my current angular 7 application we are struggling with a component from a library, which requires some css ressources. We do not want to apply those ressources to all the rest of our application, but to one specific component, its children and grandchildren.

During our research we found these two interesting options:

encapsulation: ViewEncapsulation.Native

and:

encapsulation: ViewEncapsulation.ShadowDom

In consequence, they both seem to use the browser's shadow dom implementation.

What is the difference between those options?


Solution

  • This has been been baffling me days ago, then I realized that they converge a little but not totally. The dissimilarity in fact is about the newer version of shadowDOM (v1). As you can see here in angular's code source they added an other condition for the ViewEncapsulation.ShadowDom:

    Here they share the same return

     case ViewEncapsulation.Native:
     case ViewEncapsulation.ShadowDom:
          return new ShadowDomRenderer(this.eventManager, this.sharedStylesHost, element, type);    
    

    And then they check whether it is ViewEncapsulation.ShadowDom or not (else condition)

         if (component.encapsulation === ViewEncapsulation.ShadowDom) {
              this.shadowRoot = (hostEl as any).attachShadow({mode: 'open'});
            } else {
              this.shadowRoot = (hostEl as any).createShadowRoot();
            }
    

    Thus, ViewEncapsulation.ShadowDom is a step to add a support to ShadowDOM V1, and maybe deprecate the ViewEncapsulation.Native as described here:

    ViewEncapsulation.Shadow is added as a new API, rather than changing the behavior of the ViewEncapsulation.Native option, which could lead to unexpected results for developers currently using the v0 API. This should (eventually?) deprecate the ViewEncapsulation.Native option.