Encountering a situation where d3.events is returning null within Angular 2 TypeScript code

Seeking to enhance my d3 maps with tooltips, I came across a helpful code snippet at this link

However, upon implementing the same code in an Angular 2 TypeScript file, an error emerged:

Error: Cannot read property 'transition' of undefined

The issue arises from d3.event being null and not working as expected in JavaScript code. Here's a snippet of my ngAfterViewInit method:

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") // Error occurs here
                    .style("top", (d3.event.y - 28) + "px");
            })
           .on('mouseout', function (d, i) { d3.select(this).style({ fill: 'black' }); });

    }

/* Custom Tooltip Styling */
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;         
}

Answer №1

To include the event from d3, follow the code snippet below:

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

Answer №2

Your piece of code

this.div.transition()

Resides within a function that could potentially lose reference to this depending on how it is invoked.

Solution:

Consider using an arrow function.

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

Learn More

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one use an Angular Route to navigate to a distinct URL? Essentially, how does one disable matching in the process?

I'm working on a front-end Angular application and I need to add a menu item that links to an external website. For example, let's say my current website has this URL: And I want the menu item in my app to lead to a completely different website ...

Issue: Incorrect hook usage. Hooks are designed to be used within the body of a function component. This error may occur due to one of the following reasons: 1

I've reviewed similar questions and attempted to apply the solutions provided, but it seems I'm missing something specific to my situation. My goal is to streamline my code by importing headers from a utils file and using them across different AP ...

Using *ngFor to populate an array in an ion-list within Ionic 2

Hi there, I'm currently learning Ionic 2 and I recently created an array that I want to loop through in an ion-list. This is my produk.ts import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angul ...

Having trouble establishing a connection with Db2 while using protractor

Encountering an issue when attempting to establish a connection with a remote DB2 database, resulting in the following exception: SQL30081N A communication error has been detected. The communication protocol in use is 'TCP/IP'. The com ...

Angular is experiencing difficulty booting up correctly

Upon opening it in my browser, an error message is displayed and the pages fail to load. core.js:4197 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status" ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

"Mastering the art of displaying real-time data on a thermometer using D3.js

Welcome to the sample code for a thermometer created using D3.js. You can view the code on jsfiddle. I've developed a web page displaying a dynamic thermometer with values updating every second. Here's the function: setInterval(function(){ getN ...

Error: Angular project unable to locate Auth0 module

I recently forked the Auth0 repository (specifically for Angular) based on their instructions found on GitHub. After running npm install in the root folder, I encountered an error at the end of the process where webpack outputted the message: "Cannot fin ...

What could be causing the Angular input [value] to execute the function() repeatedly?

While working on a simple code snippet to display input values from an array in a Typescript HTML template, I encountered an issue where the data wasn't loading quickly enough, resulting in errors until it was fully loaded. To solve this problem, I ad ...

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...

Using Fixed Patterns and Combining Types in an Interface

Presently, I am working with this interface: export interface User{ name: string birthday: number | Timestamp ... } When strictTemplates:false is enabled, I have no issue using this interface for server data retrieval with the birthday parameter in ...

Using the increment operator within a for loop in JavaScript

this code snippet causes an endless loop for (let i = 0; ++i;) { console.log(i) } the one that follows doesn't even run, why is that? for (let i = 0; i++;) { console.log(i) } I want a thorough understanding of this concept ...

Enhance your social interactions by incorporating a custom interaction field using Google Analytics

At times, I have two share buttons in the user interface of my application (depending on the state). These buttons can share the same data but are located in different parts of the UI. The goal is to analyze from which button (part of UI) the share action ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

Obtain text output from an Observable

After retrieving a String from the backend: String value = "{I am here}"; In my service method: getValue(): Observable<String> { return this.http.get<String>(this.myURL); } In my component, I am subscribing to this method: String myM ...

Angular reloads content when language is switched

I am facing an issue with my language selector and default pipes for number or currency format. Even after changing the language (e.g., from en-US to fr-FR), the thousands separator remains unchanged despite the correct updates in LOCALE_ID and TranslateSe ...