D3 v4 drag and drop with TypeScript

I am using D3 v4 and Angular2 library and I want to do svg elements drag and drop. I have a code:

item.call(
    d3.drag()
      .on("start", dragStarted)
      .on("drag", dragged)
      .on("end", dragEnded)
  );

      

and

function  dragStarted(d) {
    d3.select(this).raise().classed("active", true);
}

function  dragged(d) {
    d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function  dragEnded(d) {
    d3.select(this).classed("active", false);
}

      

I am getting this error:

TS2345: argument of type 'DragBehavior' is not assigned to parameter type '(selection: Selection, ... args: any []) => void'. The "selection" and "selection" parameter types are not compatible. The Select type cannot be assigned to the Select type. The "BaseType" type is not assigned to the "Element" type. The "EnterElement" type is not assigned to the "Element" type. Property 'classList' is missing in type 'EnterElement'.

Any ideas?

+2


source to share


2 answers


I tried to code this example , but it shows the same error. I write it differently:

svg.selectAll("circle")
    .data(circles)
    .enter().append("circle")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", radius)
    .style("fill", 'blue');

svg.selectAll("circle").call(d3.drag().on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

      



And it works for me.

+2


source


Please see my answer in response to a similar issue post here .

It explains the need for and approach to ensuring that the drag behavior and the selection it operates on have compatible base element types and associated data types.



Following the steps outlined here, adapted to your situation, will fix the issue.

+1


source







All Articles