Angular Q&A: How does View Encapsulation work with Shadow DOM and Emulated?

In Angular, view encapsulation determines how styles defined in a component are applied to the component's template. By default, Angular uses a strategy called "Emulated" view encapsulation, which applies the styles defined in a component to the component's template, but also allows the styles to be applied to elements in the parent component's template.

If you want to use the Shadow DOM to apply styles in a more scoped and encapsulated way, you can use the ViewEncapsulation.ShadowDom option when defining a component. This will tell Angular to use the Shadow DOM to apply styles to the component's template, rather than the emulated view encapsulation strategy.

For example, here is how you might define a component that uses Shadow DOM view encapsulation:

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

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class ProductListComponent { }

With this configuration, the styles defined in the product-list.component.css file will be applied to the ProductList component's template using the Shadow DOM. This will create a new Shadow DOM subtree for the component, and the styles will be applied to elements within the component's template, but not to elements in the parent component's template.

💡
Want to sponsor matcha.fyi? You can have your brand featured right here. Let's connect and chat about it.