Native encapsulation using Shadow DOM

As an alternative to the CSS Encapsulation, Angular also features another great namespace-like feature using its unique Shadow DOM implementation.

Explaining what the Shadow DOM actually is in a few words is another impossible task, yet we'll try to do that nonetheless; Shadow DOM is one of the four Web Component standards, along with HTML Templates, Custom Elements, and HTML Imports. It allows whoever uses it (the developer or the underlying framework) to hide DOM logic behind other elements, thus enabling--among many other things--CSS scoping and DOM encapsulation.

If you want to know more about Web Component and Shadow DOM, we strongly suggest that you read this awesome article by Eric Bidelman at https://developers.google.com/web/fundamentals/architecture/building-components/shadowdom.

To cut it short, Angular can (optionally) use the Shadow DOM to wrap any given component into a dedicated rendering context, thus isolating it from the rest of the DOM; as a result, all the CSS stylings will also be encapsulated into that limited scope.

This optional feature is called Native Encapsulation and can be activated using the ViewEncapsulation enum within the @Component part of the component class file.

Let's give it a try within our quiz-search.component.ts file (new lines are highlighted):

import { Component, Input, ViewEncapsulation } from "@angular/core";

@Component({
selector: "quiz-search",
templateUrl: './quiz-search.component.html',
styleUrls: ['./quiz-search.component.css'],
encapsulation: ViewEncapsulation.Native
})

export class QuizSearchComponent {
@Input() class: string;
@Input() placeholder: string;
}

We can see the results by giving our project another run and inspecting the HTML, like we did earlier:

It's worth noting that this time we had to use Google Chrome, since it's the only web browser supporting native Shadow DOM as of today. Trying to do that with Edge will result in the following error:

TypeError: Object doesn't support property or method 'createShadowRoot'

We can see how the rendering engine wrapped our component's contents within a #shadow-root pseudo-element containing all the stylings. By looking at the rendering results, we can easily note that this alternative approach is way more drastic than the default one; the component is completely isolated, hence it doesn't inherit the Bootstrap default styles and just outputs as standard HTML.

We definitely don't want to use this behavior, hence we will need to rollback the changes we made on our QuizSearchComponent class; however, before doing that, let's do one more quick test.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.186