Styles in component for D3.js do not show in angular 2

Update

Angular and SASS agreed on supporting ::ng-deep (instead of >>> or /deep/) a while ago until ::slotted or whatever makes it into browser standards becomes available in all browsers.

ViewEncapsulation.Emulated (default)

That’s by design. Angular adds class names unique to components and rewrites the added styles to only apply to the components where they were added.

D3 generates HTML dynamically without Angulars knowledge and Angular can’t apply the classes to make the styles apply on the generated HTML.

If you add the styles at the entry point HTML file, Angular also doesn’t rewrite the styles and the added helper classes don’t take effect.

ViewEncapsulation.None

With encapsulation: ViewEncapsulation.None Angular doesn’t do this rewriting, therefore the result is similar to adding the HTML to the index.html.

“Shadow-piercing”

Alternatively you can use the recently introduced shadow piercing CSS combinators >>>, /deep/ and ::shadow (::shadow is just replaced by a and thus very limited). See also https://stackoverflow.com/a/36225709/217408 and the Plunker

:host /deep/ div {
  color: red;
}

SASS

/deep/ works fine with SASS but the alias >>> doesn’t.

The shadow-piersing CSS combinators are rewritten by Angular and they don’t need to be supported by the browsers. Chrome supported them for a while but they are deprecated – but as said, that doesn’t matter, because Angular rewrites them to use its encapsulation emulation.

ViewEncapsulation.Native

Angular doesn’t support any way to style such components from the outside. Only if the browser provides support like CSS variables then these can be used.

Leave a Comment