I can't access the _groups property in angular/d3js

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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);
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply