What is the best way to reference class variables and methods within a callback function in Typescript?

While working on my Angular project with the Highcharts API, I encountered a situation where I needed to pass a state code to a class level method after drilling down to a specific map location.

Below is the snippet of my current code:

ngOnInit() {

this.chartOptions = {
  chart: {
    height: (8 / 16) * 100 + '%',
    events: {
      drilldown(e) {
        // ERROR Error: this.getVendorProductStatsByStateCode is not a function
        this.getVendorProductStatsByStateCode(e.point.drilldown);
        const chart = this as any;

        const mapKey = 'countries/ca/' + e.point.drilldown + '-all';
        const mapData = require(`@highcharts/map-collection/countries/ca/ca-on-all.geo.json`);
        const provinceData = Highcharts.geojson(mapData);
        provinceData.forEach((el: any, i) => {
          el.value = i;
        });

        chart.addSeriesAsDrilldown(e.point, {
          name: e.point.name,
          data: provinceData,

          dataLabels: {
            enabled: true
          }
        });

        chart.setTitle(null, { text: e.point.name });
      },
      drillup() {
        const chart = this as any;
      }
    }
  },
  title: {
    text: ''
  },
  colorAxis: {
    min: 0,
    minColor: '#E6E7E8',
    maxColor: '#417BCC'
  },

  mapNavigation: {
    enabled: true,
    buttonOptions: {
      verticalAlign: 'bottom'
    }
  },
  plotOptions: {
    map: {
      states: {
        hover: {
          color: '#F8BA03'
        }
      }
    }
  },
  series: [
    {
      name: 'Canada',
      data: caMap
    }
  ],
  drilldown: {}
};
}

getVendorProductStatsByStateCode(mapstateCode) {
    console.log(mapstateCode);
}

Here is the live example on StackBlitz

When invoking the drilldown function, I aim to access

this.getVendorProductStatsByStateCode
, which resides in one of my class component methods. What would be the correct approach to achieve this?

Answer №1

If you want to avoid using "this" as a reference to your component, you can store it in a variable and then use that variable instead. Here's an example:

  caMap.forEach((el: any, i) => {
      el.value = i;
      el.drilldown = el.properties['hc-key'];
    });
    var myComp = this;
    this.chartOptions = {
      chart: {
        height: (8 / 16) * 100 + '%',
        events: {
          drilldown(e) {
            // ERROR Error: this.getVendorProductStatsByStateCode is not a function
            myComp.getVendorProductStatsByStateCode(e.point.drilldown);
            const chart = this as any;

            const mapKey = 'countries/ca/' + e.point.drilldown + '-all';
            //Stackbliz wont load data if you pass mapkey as variable. So I use a hard code one in this example.
            // const mapData = require(`@highcharts/map-collection/${mapKey}.geo.json`);
            const mapData = require(`@highcharts/map-collection/countries/ca/ca-on-all.geo.json`);
            const provinceData = Highcharts.geojson(mapData);
            // Set a random value on map
            provinceData.forEach((el: any, i) => {
              el.value = i;
            });

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

What is the reason for the request to accept */* when the browser is seeking a JavaScript file?

The html source appears as follows: <script type="text/javascript" language="JavaScript" src="myscript.js"></script> Upon debugging the http request using Fiddler, it is evident that the browser (Chrome) sends a GET request for myscript.js wi ...

Having trouble exporting a static HTML file using Next.js

https://i.stack.imgur.com/xQj7q.pngI'm a beginner in the world of React. Recently, I completed a project where I utilized "next build && next export" in my package.json file for static HTML export. By running the npm run build command, an out folder w ...

Angular 5 Dilemma: Exporting UI Components without Locating Template

My current project involves developing UI Components that will be used in various web projects within the company. Our plan is to publish these UI components as an npm package on our local repository, and so far, the publishing process has been successful. ...

Validation method in jQuery for a set of checkboxes with distinct identifiers

I am faced with a situation where I have a set of checkboxes that, due to the integration with another platform, must have individual names even though they are all interconnected. <div class="form-group col-xs-6 checkbox-group"> <label cla ...

@The value of @Input is consistently undefined

I'm using @Input to pass IDs into a child component, where they are used to filter the data set within that component. <div *ngIf="exerciseLength > 0"> <exercise [course]="Course" [filter-by-exercise-id]=""></exercise> </di ...

Error encountered: Javascript throws an error while trying to initialize the Bootstrap datetimepicker if the input value only

My requirement is to utilize the DateTime Picker plugin and load only the Time picker component. To achieve this functionality, I have initialized my input field in the following manner, allowing only time selection: jsfiddle: <div class="input-group ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

Issue occurs where the system is unable to recognize a defined variable, despite it being clearly defined

I keep encountering an error message stating that my variable is not defined, even though I have clearly defined it just a few lines above where the error occurs. The reason behind this error is baffling to me, as I cannot identify any potential triggers ...

Object autofill - Typescript utilizing Angular 5

I am working with an object called "features." Here is an example of the object: [{"_id":"5af03d95c4c18d16255b5ac7","name":"Feature 1","description":"<p>Description</p>\n","neworchange":"new","releaseId":"5aead2d6b28715733166e59a","produc ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

Use a route segment as the callback argument

I am new to working on my first express app. I am wondering if there is a way to pass a route segment as an argument to a callback? app.get('/connect/:mySegment', myCallback(mySegment)); For example, I am utilizing passport with multiple authen ...

Transferring Information Between Components

After logging into my login component, I want to pass data to my navbar component but unfortunately, my navbar content does not update. The navbar component is located in the app-module while the login component is in a separate module. I attempted to us ...

React hooks causing the for loop to only work on the second iteration

I am working on a project where I need to implement tags, similar to what you see on this website. Before adding a tag, I want to ensure that it hasn't already been selected by the user. I have set up a for loop to compare the new tag with the existin ...

Leveraging Java and TypeScript code for specific functionalities within an Ionic 2 Android application

When it comes to creating hybrid apps that support Windows, iOS, and Android simultaneously using web technologies such as Html, CSS, and Js, Ionic is the go-to choice. However, there may be certain features not supported by the Ionic 2 framework. Is it ...

Using the swiper carousel on WordPress results in an unexpected horizontal scrolling issue

Running an Elementor website, I need to incorporate various image carousels within my post content. Initially, I created a template for each carousel using Elementor. However, I have now decided to switch to utilizing a shortcode that leverages Elementor&a ...

Retrieve data in JSON format from an external source file

I've been attempting to retrieve JSON content from an external file named list.json, but unfortunately all of my efforts have been unsuccessful. I've created a prototype of my code on Jsfiddle (http://jsfiddle.net/ctmvcyy1/). I believe that the ...

Trigger the opening of a class or window upon pressing the button

Good evening, I'm attempting to create a functionality where pressing a specific button will open a window. However, I am unsure of how to achieve this using CSS classes. My initial thought was to add a new class in the CSS file and call it every ti ...

Implement a class in Typescript that allows for the addition of properties at runtime

I'm currently in the process of incorporating Typescript definitions into an existing codebase that utilizes the Knockout library. Within the code, there is a prevalent pattern that appears as follows: interface SomeProperties { // Assorted prope ...

Access the current page's URL using JavaScript

I have a unique URL structure that looks like this: index.html#page:page.php As I am loading my pages dynamically using AJAX, I want to create hotlinks to load specific pages. Currently, I am using the following function: function getdata(file){ $ ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...