1

I have a problem accessing my "_groups" property with the following code:

function mouseDate(scale){ 
        var g = d3.select("#group")._groups[0][0]

        var x0 = scale.invert(d3.mouse(g)[0]);

        console.log(x0);
    }

Result of my console.log:

Selection {_groups: Array(1), _parents: Array(1)}
  _groups: Array(1)
    0: Array(1)
      0: g#group

When I compile the code I have the following error :

D:/Documents/starter-propre-angular4/src/app/pages/graphe-page/graphe.page.ts (782,32): Property '_groups' does not exist on type 'Selection<BaseType, {}, HTMLElement, any>'.

So my question is: Is there a solution to get the information in "_groups" all year round knowing that I am evolving into TypeScript using d3js

Headan
  • 13
  • 2

1 Answers1

2

The _groups property is a private member of a Selection object and should as such not be accessed directly. (Side note: it is common convention in JavaScript that any member starting with an underscore denotes a private member. See, e.g., "Underscore prefix for property and method names in JavaScript").

Since the property is considered private it is not part of the public interface and is therefore not included in the TypeScript type declaration for the d3-selection module. Hence, you get the compiler error you witnessed. Although this actually will work in pure JavaScript the TypeScript compiler did exactly what it is supposed to do—namely, prevent you from doing some unsafe stuff.

Looking at the code you posted, though, it becomes apparent that you are not interested in the _groups property itself but rather in _groups[0][0] which internally refers to the first node of the selection. Fortunately, the selection.node() method will return exactly that first element. You can do it like this:

function mouseDate(scale){ 
  var g = d3.select("#group").node();
  var x0 = scale.invert(d3.mouse(g)[0]);
  console.log(x0);
}
altocumulus
  • 19,180
  • 11
  • 55
  • 76