d3.js - angular2: apply class to d3 element from component's style -


having component in angular2 app.component.css defines class h-bar:

enter image description here

in app.component.ts, d3 used generate elements applies class h-bar app.component.css.

d3.select("#container").selectall("div.h-bar") // <- c                 .data(data) // <- d                 .enter() // <- e                 .append("div") // <- f                                 .attr("class", "h-bar")                                 .append("span"); // <- g     

however style has not been rendered properly. looking html generated, found random _ngcontent-baf-1 (not sure if module.id) missing elements generated d3.

enter image description here

so add attribute module.id these element:

// enter             d3.select("#container").selectall("div.h-bar") // <- c                 .data(data) // <- d                 .enter() // <- e                 .append("div") // <- f                           .attr(module.id, "")                                       .attr("class", "h-bar")                                 .append("span"); // <- g  

unfortunately error thrown module.id invalid attribute name:

enter image description here

any idea please?

encapsulated styles work dom objects handled angular.

i'd suggest turning off encapsulation on component:

@component({   ...,   encapsulation: viewencapsulation.none }) 

however, pollute global css namespace, ids/classes should unique component.

to keep encapsulation, try this:

  constructor(private hostref: elementref) { }    ngoninit() {     this.ngcontentid = '_ngcontent-' + this.hostref.nativeelement.attributes[1].name.substr(8);   }    addstuff(){     d3.select("#container").selectall("div.h-bar") // <- c       .data(data) // <- d       .enter() // <- e       .append("div") // <- f                 .attr(this.ngcontentid, "")       .attr("class", "h-bar")       .append("span"); // <- g    } 

this quick , dirty, don't know, if host id attributes[1]. might vary, you'd have loop through attributes find right one.


Comments