04 Angular Css Selectors - juanfevasquez/Ng-BasicStyling GitHub Wiki

Go to Previous Page

Angular Special Css Selectors (Shadow DOM selectors)

On branch: demo/Angular-css-selectors

Working with a simulated Shadow DOM functionality (Emulated View Encapsulation) brings a new set of challenges. Some of these challenges are easy to solve thanks to the Shadow DOM Css selectors. These selectors allow us to work with more precision within our encapsulated css and even react to changes outside the scope of our component like for example, how would our encapsulated component's styles change if a global theme variable was changed?

With Shadow DOM selectors we can still allow our global css to influence the behavior of our scoped styles, let's see the different selectors that exist.

Note: change to branch demo/Angular-css-selectors

:host

If you want to add styles to the root of your component, you have to use :host to point to it. For example, in our card.component.css, we want to add to our root tag, , some styles. We can't just say app-card{...}, no no. :host is here to help us with that

:host {
  position: relative;
  width: 100%;
  max-width: 300px;
  padding: 5px;
  margin: 0 5px 15px;
  background-color: white;
}

:host-context(selector)

This selector allow us to add styles depending on a match on our ancestors going up to the document root. In the following example, we change the background of our cards IF any ancestor has a class named .dark-theme:

:host-context(.dark-theme) {
  background-color: black;
  color: #f5f5f5;
}

Shadow DOM piercing selectors

What if, for some weird and probably unjustified reason, we need to pierce through our Shadow DOM to add some styles to a child component with ViewEncapsulation enabled?

There is the :host ::ng-deep selector. Let's say we want to add some styles to our cta component from our card.component.css. From the branch demo/Angular-css-selectors we have this scenario. I converted the call to action into its own component , and added it into the card component. Let's try changing its background color from card.component.css.

:host ::ng-deep a.cta {
  background-color: yellowgreen;
}

IMPORTANT! The Angular team has plans to deprecate this functionality including all of its syntax which are:

  • :host /deep/
  • :host >>>
  • :host ::ng-deep

According to the oficial documentation, we shouldn't try using this, but if we have to, it is recommended to go with ::ng-deep.

Next: How external css files are loaded

⚠️ **GitHub.com Fallback** ⚠️