Angular

Last Updated: 8/21/2023

View Encapsulation

  • Styles applied to the angular component are scoped to the component, they will not leak outside of the component template.
  • If you are building a component - you are going to apply some styles to the component - you want to ensure that those styles are scoped to your component
  • If you want to use a component built by someone else, they might have defined some styles under the component, if you bring that component in your application, you don't want those styles to override the styles in your application.

Shadow DOM

  • Shadow DOM is a specification that enables DOM tree and style encapsulation
  • Allows us to apply scoped styles to elements without bleeding out to the outer world
  • Only supported in certain browser

Style leaks outside

var el = document.querySelectory("favorite");
el.innerHTML - `<style>h1{color: red}</style><h1>Hello</h1>`

Shadow DOM

var el = document.querySelector("favorite");
var root = el.createShadowRoot();
root.innerHTML - `<style>h1{color: red}</style><h1>Hello</h1>`

Encapsulation

  • In @Component Decorator add
encapsulation: ViewEncapsulation.Emulated (Default) | Native | None
  • Emulated:
    • Emulates shadow DOM.
    • As most browser doesn't support it, angular attaches attributes to element and use that to post process the CSS rules
    • It works by attaching additional attributes to our CSS rules
  • Native:
    • Uses ShadowDOM in browser
    • Chrome developer tool > Setting > Elements > Show user agent shadow DOM
    • For some styles to work we need to import the parent styles
    • Not recommended. Creates performance problem.
  • None:
    • Styles leak outside the component