Search code examples
javascriptcssangularsassng-deep

How to apply styling to shadow root element in angular


I am using angular 12 and I want to apply some styling to input field which is a shadow root element of group-search-field element.

enter image description here

I tried using ng-deep like below but it didn't work

:host ::ng-deep input {
  background: red !important;
}
Can someone guide me for this ?


Solution

  • Because of the isolation of styles, which is a feature of Shadow DOM, you cannot define a global CSS rule that will be applied in the Shadow DOM scope. In your case I think background:red does not propagate to be inherited by the elements in the shadow root that's why :host is not working.

    super();
    const shadowRoot = this.attachShadow({ mode: 'open' });
    const sheet = new CSSStyleSheet;
    sheet.replaceSync( `input { background: red !important; }`)
    shadowRoot.adoptedStyleSheets = [ sheet ];
    

    https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM