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.
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:
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.