D3 v4 - cannot read null property text

I tried to convert a good D3 diagram example ( https://jsfiddle.net/thudfactor/HdwTH/ ) into an Angular2 component with the new D3 v4.

However, I get an exception "cannot read the text of the null property" with the following code:

var textLabels = labelGroups.append("text").attr({ x: function (d, i) { var centroid = pied_arc.centroid(d); var midAngle = Math.atan2(centroid[1], centroid[0]); var x = Math.cos(midAngle) * cDim.labelRadius; var sign = (x > 0) ? 1 : -1 var labelX = x + (5 * sign) return labelX; }, y: function (d, i) { var centroid = pied_arc.centroid(d); var midAngle = Math.atan2(centroid[1], centroid[0]); var y = Math.sin(midAngle) * cDim.labelRadius; return y; }, 'text-anchor': function (d, i) { var centroid = pied_arc.centroid(d); var midAngle = Math.atan2(centroid[1], centroid[0]); var x = Math.cos(midAngle) * cDim.labelRadius; return (x > 0) ? "start" : "end"; }, 'class': 'label-text' }).text(function (d, i) { <--------------- exception return d.data.label; }); 

labelgroups is the choice, adding should work, so the .attr({}) problem should occur. However, it works fine in jsfiddle.
Is this syntax changed in D3 v4? How will it be right?

Thanks!

+7
javascript
source share
1 answer

In the new D3 v4.x, you cannot use objects to install attr or style . To do this, you need to turn to the D3-selection-multi mini-library:

 <script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script> 

After that, change the code from attr to attrs (yes, like the plural):

 var textLabels = labelGroups.append("text").attrs({ //all the key-value pairs here }); 

Do the same for styles: it should be styles , like plural, not style .

If you don’t want to change all this, just follow the “normal” method: set x , y , text-anchor and class to a separate attr .

Here is the selection-multi documentation: https://github.com/d3/d3-selection-multi/blob/master/README.md#selection_attrs

+15
source share

All Articles