Managing view encapsulation

All the preceding sections (styles, styleUrls, and inline style sheets) will be governed by the usual rules of CSS specificity (https://developer.mozilla.org/en/docs/Web/CSS/Specificity). CSS management and specificity becomes a breeze on browsers that support Shadow DOM, thanks to scoped styling. CSS styles apply to the elements contained in the component, but they do not spread beyond its boundaries.

On top of that, Angular will embed these style sheets at the head of the document, so they might affect other elements of our application. In order to prevent this from happening, we can set up different levels of view encapsulation.

In a nutshell, encapsulation is the way Angular needs to manage CSS scoping within the component for both shadow DOM-compliant browsers and those that do not support it. For all this, we leverage the ViewEncapsulation enum, which can take any of these values:

  • Emulated: This is the default option, and it basically entails an emulation of native scoping in Shadow DOM, through sandboxing the CSS rules under a specific selector that points to our component. This option is preferred to ensure that our component styles will not be affected by other existing libraries on our site.
  • Native: Use the native Shadow DOM encapsulation mechanism of the renderer, and it only works on browsers that support Shadow DOM.
  • None: Template or style encapsulation is not provided. The styles will be injected as is into the document's header.

Let's check out an actual example. First, import the ViewEncapsulation enum into the script, and then create an encapsulation property with the emulated value. Then, let's create a style rule for our countdown text so any <h1> (!) tag is rendered in dark red:

import {
Component,
EventEmitter,
Input,
Output,
ViewEncapsulation
} from '@angular/core';
@Component({
selector: 'countdown-timer',
template: '<h1>Time left: {{seconds}}</h1>',
styles: ['h1 { color: #900}'],
encapsulation: ViewEncapsulation.Emulated
})
export class CountdownTimerCoponent {
// Etc
}

Now, click on the browser's dev tools inspector and check the generated HTML to discover how Angular injected the CSS inside the page <head> block. The just injected style sheet has been sandboxed to ensure that the global CSS rule we defined at the component setup in a very non-specific way for all <h1> elements only applies to matching elements scoped by the CountdownTimerComponent component exclusively.

We recommend that you try out different values and see how the CSS code is injected into the document. You will immediately notice the different grades of isolation that each variation provides.

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

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