Getting d3.events as null in angular2 typescript c

2019-09-19 08:03发布

问题:

I am implementing tooltip in my d3 maps using the code from link http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922

When I write the same code in my angular 2 typescript file. I get error:

Cannot read property 'transition' of undefined

it is basically not able to find d3.event (getting it as null) which does not happen in javascript code. My code in ngAfterViewInit

ngAfterViewInit() {
        this.tooltip = d3.select("map-tag")
            .append("div")
            .attr("class", "tooltip")
            .style("opacity", 0);

        this.svgContainer = d3.select("map-tag").append("svg")
            .attr("width", this.width)
            .attr("height", this.height)
            .style("border", "2px solid steelblue")
            .call(this.zoom);
        this.usaSVG = this.svgContainer
            .append("path")
            .attr("d", this.geoPath(this.usaFeatureCollection))
            .style({ fill: "none", stroke: "black" });

        this.geoPoint1 = {
            "type": "MultiPoint", "coordinates": [[-80.6665134, 35.0539943]]
        };
        this.div = d3.select("map-tag")
            .append("div")
            .attr("class", "tooltip")
            .style("opacity", 0);
        this.pointPath = this.svgContainer.append("path").attr("d", this.geoPath(this.geoPoint1)).style("stroke", "#FFFFFF")
            .on('mouseover', function (d, i) {
                this.div.transition()
                    .duration(200)
                    .style("opacity", .9);
                this.div.text("sample text")
                    .style("left", (d3.event.x) + "px") // I get error here
                    .style("top", (d3.event.y - 28) + "px");
            })
           .on('mouseout', function (d, i) { d3.select(this).style({ fill: 'black' }); });

    }

/* Style for Custom Tooltip */
div.tooltip {   
    position: absolute;           
    text-align: center;           
    width: 60px;                  
    height: 28px;                 
    padding: 2px;             
    font: 12px sans-serif;        
    background: white;   
    border: 0px;      
    border-radius: 8px;           
    pointer-events: none;         
}

回答1:

You need to import event from d3 as below :

Import {event, BaseEvent} from "d3-selection"



回答2:

Your code

this.div.transition()

Is inside the function that might loose this based on how it gets called.

Fix:

Use an arrow

.on('mouseover', (d, i) => {
                this.div.transition()
                    .duration(200)
                    .style("opacity", .9);
                this.div.text("sample text")
                    .style("left", (d3.event.x) + "px") // I get error here
                    .style("top", (d3.event.y - 28) + "px");
            })

More

https://egghead.io/lessons/typescript-catch-unsafe-use-of-this-in-typescript-functions