问题
I am using the D3 library v4 and Angular2 and I want to make a drag and drop of svg elements. 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 get this error:
TS2345: Argument of type 'DragBehavior' is not assignable to parameter of type '(selection: Selection, ...args: any[]) => void'. Types of parameters 'selection' and 'selection' are incompatible. Type 'Selection' is not assignable to type 'Selection'. Type 'BaseType' is not assignable to type 'Element'. Type 'EnterElement' is not assignable to type 'Element'. Property 'classList' is missing in type 'EnterElement'.
Any ideas?
回答1:
I tried to use code from this sample but it show the same error. I write it in another way:
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:
Please see my answer in response to a similar SO issue post here.
It explains the need for and approach to ensuring that the drag behavior and the selection it operates on have compatible underlying element types and bound data types.
Following the steps outlined there, adapted to your situation, will address the issue.
回答3:
I'm still not sure what's the most correct way to both avoid compilation error but also avoid faking the type system... But it seems working even in the following way:
this.svgGraph
.append('line')
.call(d3.drag<SVGLineElement, unknown>()
.on('drag', this.dragged())
);
so 'forcing' the type SVGLineElement.
what do you think?
来源:https://stackoverflow.com/questions/43992586/d3-v4-drag-and-drop-with-typescript