In this example, we have a component, our panel, which has some styles associated via the styleURLs property. One of the main challenges in creating proper isolated and reusable components is to avoid leaking styles to other components.
Let's go into the app component HTML, where we define our isolated component, and let's create here a div which uses the same kind of class that we have defined inside our isolated component. "I am outside the isolated component." Great.
If we save this here, we see that the style doesn't seem to get applied to our div outside here. This might come strange initially, but let's take a look at how the styles are being rendered by Angular. Let's look at the panel style.
We see the class has been applied correctly to our component, but if we take a close look at how the styles are being embedded in our application, we note that we get this suffix here. Angular basically takes our style class, and then suffixes adhere with this tag, which is actually the tag that has been dynamically added to our div of our component.
In this way, it isolates the style, and it won't get applied to this div below, which has the same kind of class as we have specified inside our component. This is actually something we want to achieve in an isolated and component-oriented design.
By default, Angular activates this isolation. It does it by the so-called emulated mode. Let's take a look. We can go here and import the ViewEncapsulation property directly from the Angular core package. Then our components have a property called encapsulation, which takes a ViewEncapsulation.
By default, as we have mentioned, we have emulated, which adds those prefixes when rendering the style onto our site. If we add, for instance, known, we are deactivating this isolation. Now, as you can see, the style leaks outside of our component, and gets also applied to our div, which has the same kind of CSS class as our component inside here.
The third possibility we have is to use native. What native does is it again isolates our styles, but now it uses the native shadow DOM property, which is available in modern web browsers, and which is a native implementation for Web components.
If you open up that shadow root, we see two kind of elements inside there. We have the plain HTML code of our component. No autogenerated texts that have been added, but just the plain HTML part. We also have a style element which contains our CSS code.
The shadow root basically scopes this HTML code and also the styles directly to our component. While the emulated mode works across browsers without any issues, make sure that your current browser that you're targeting supports the shadow DOM.