user3431310
user3431310

Reputation: 871

Implementing d3.js in angular 4

I am drawing polygon by using mouse. I managed to do the code using normal javascript file. Now I want to implement the same thing in my typescript file

This is my d3.js file

//D3.JS VERSION 3
//---------------------------
var dragger = d3.behavior.drag()
.on('drag', handleDrag)
.on('dragend', function(d){
    dragging = false;
});


function handleDrag() {
    if(drawing) return;
    var dragCircle = d3.select(this), newPoints = [], circle;
    dragging = true;
    var poly = d3.select(this.parentNode).select('polygon');
    var circles = d3.select(this.parentNode).selectAll('circle');

    for (var i = 0; i < circles[0].length; i++) {
        circle = d3.select(circles[0][i]);
        newPoints.push([circle.attr('cx'), circle.attr('cy')]);
    }
      poly.attr('points', newPoints);

          console.log('newPoints', newPoints);
    dragArea = d3.polygonArea(newPoints);
    console.log('dragArea',dragArea);
     d3.select("#toolTipArea").text('Area = '+dragArea+' sqft');

    dragCircle
    .attr('cx', d3.event.x)
    .attr('cy', d3.event.y)
        .on("mousemove", function(){return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+10)+"px").text(""+dragArea+"sqft")})
        .on("mouseout", function(){return tooltip.style("visibility", "visible").text(""+dragArea+"sqft")})
        .on("mouseover", function(){return tooltip.style("visibility", "visible").text(""+dragArea+"sqft")});
        //         .on("mousemove", tooltipMaster(1))
        // .on("mouseout", tooltipMaster(2))
        // .on("mouseover", tooltipMaster(3));

}

This code work fine in normal html n js file.
Now I want to implement this code in my angular4.But, I got few problems in my typescript file.I have installed the latest d3.js version, version 4.

1)First problem is

I need to change my d3.behavior.drag() function because, it is not supported in version 4. So I changed to:-

     this.dragger = d3.drag()
         .on("drag", this.handleDrag())
         .on("end", this.endDrag()); 

2)and this is the handleDrag() (which lies the second problem) enter image description here

Like it shows, I got problem at .this, this.parentNode etc
so how should I call .this/this.parentNode in angular(in normal js file it works).

3)Showing this error at:- enter image description here


So , I got all this error when I want to implement the normal d3.js function into my ts file , angular 4. I need to know the proper way to call in angular.
Thank you.

Upvotes: 0

Views: 424

Answers (1)

Blue
Blue

Reputation: 22911

Make sure you pass the actual function and not the return value of the function, by eliminating the ():

 this.dragger = d3.drag()
     .on("drag", this.handleDrag)
     .on("end", this.endDrag); 

For your other issue, use (this as any).parentNode to allow this to be treated as any object to avoid typescript issues.

Upvotes: 1

Related Questions