A helpful guide on invoking a TypeScript function within a Highcharts click event

MyCustomHighChart.ts

export class MyCustomHighChart {
    highchartsConfiguration: any = {
        chart: {
            events: {
                click(event) {
                    if (!($(event.target)[0].textContent)) {
                        console.log('clicked'); //this message is being displayed
                        this.callDrillDown(); // Is it possible to invoke a TypeScript function here?
                    }
                },
            },
        }
    };  

    callDrillDown() {
      console.log('calling drill down method');
    }
}

Is there a way to trigger a typescript function within a high charts click event?

I encountered the following error

Error Stack : TypeError: this.callDrillDown is not a function

Answer №1

For maintaining the same context (this) in the click handler, it is necessary to use an arrow function.

The code snippet would appear as follows:

export class MyHighChartComponent {
    highchartsConfiguration: any = {
        chart: {
            events: {
                click : (e) => {
                    if (!($(event.target)[0].textContent)) {
                        console.log('clicked'); //this is printing
                        this.drillDown(); // how to call typescript function here?
                    }
                },
            },
        }
    };  

    drillDown() {
      console.log('drill down method called');
    }
}

If you require access to both the chart context and the class context, you can manually store the class context in a variable (like you did before arrow functions existed).

class MyHighChartComponent {
  public highchartsConfig() {
    var that = this; // store this in a variable to use later
    return {
      chart: {
        events: {
          click: function(e) {
            if (!($(event.target)[0].textContent)) {
              console.log('clicked');
              // this variable now stores the chart
              // call methods on class using the that variable
              that.drillDown();
            }
          },
        },
      }
    };

  }
  public drillDown() {}
}

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

Implementing a Set polyfill in webpack fails to address the issues

Encountering "Can't find variable: Set" errors in older browsers during production. Assumed it's due to Typescript and Webpack leveraging es6 features aggressively. Shouldn't be a problem since I've successfully polyfilled Object.assign ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Strict mode error occurs when attempting to assign a value to ngComponentOutlet that is incompatible with the type of the lazy-loaded component

I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it. The goal is to have a compon ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

Securing JWT signatures for both server-side and client-side environments

I am looking to authenticate Salesforce's OAuth 2.0 JWT Bearer Flow using both node.js and a Browser. I have generated a public key and a private key on Windows by running the following command. openssl req -x509 -sha256 -nodes -days 36500 -newkey r ...

Incorporating essential npm packages into an Angular2 project

Lately, I integrated the ngx-bootstrap component into an Angular project that my team has been collaborating on. I'm facing a challenge in having to individually instruct team members to run npm install ngx-bootstrap --save to install the component l ...

Create various Angular applications using PowerShell for efficient development

Currently, I am in the process of developing a PowerShell script that sequentially builds three different Angular applications. However, I am running into an issue where only the first app is built and the script stops without any errors or reaching the li ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

How to Manually Update the Angular Release Version in your environment.ts File using the CLI

Within the environment.ts file, we store the release version. I am looking for a command to increment the minor version from the Command Line Interface (CLI) in order to use it within a Jenkins build job. export const environment = { … version: ' ...

The Type X is lacking essential properties found in Type Y, including length, pop, push, concat, and an additional 26 more properties. Code: [2740]

One interesting thing I have noticed is the Product interface: export interface Product{ code: string; description: string; type: string; } There is a service with a method that calls the product endpoint: public getProducts(): Observable<Product ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

Enforcing Type Safety on String Enums in Typescript Using the 'const' Assertion

I am trying to use an enum for type checking purposes. Here is the enum I have: enum Options { Option1 = "xyz", Option2 = "abc" } My goal is to create a union type of 'xyz' | 'abc'. However, when I attempt to d ...

Issue encountered while attempting to run an Angular project using the CLI: "Module not found - Unable to resolve 'AngularProjectPath' in 'AngularProjectPath'"

Just like the title suggests, I'm facing an issue with compiling my angular project. It seems to be having trouble resolving my working directory: Error: Module not found: Error: Can't resolve 'D:\Proyectos\Yesoft\newschool& ...

Setting up Angular 2 for Highcharts: A Comprehensive Guide

Having trouble implementing a highchart component in my Angular 2 project after setting it up with the latest version. I've created a linechart component directory and tried to add the chart using the <line-chart></line-chart> tag in the H ...

Issue encountered in Angular 7 regarding event handling in the parent component

Being a newcomer to Angular, I am facing difficulties in receiving events in the parent component. Despite going through several discussions, tips, and tutorials on this issue, I still can't figure out what mistake I am making... In my child componen ...

Transform React class components into function components

In my code, there is an abstract class: export default abstract class TableAction<T = any, R = any> extends React.Component<T, R> { protected abstract onClick(e: React.MouseEvent<HTMLButtonElement>): void | Promise<void>; pr ...

What is the process of declaring a method within a subclass and then retrieving it from a method within the parent class using Typescript?

I am currently working with this TypeScript code snippet: abstract class Base { static actions:Record<string,unknown> static getActions () { return this.actions } } class Sub extends Base { static actions = { bar:(bar:string ...

Disabling flow control to test an Angular app in Protractor results in an error being generated

I've been battling with this issue for quite some time now and my energy is running low. I am currently attempting to test an Angular application using protractor and async/await. The documentation suggests that I need to disable the control flow by a ...

Please indicate the generator title (for example, nx generate @nrwl/workspace:library) specifically for Angular

Currently, I am expanding my knowledge in web development. While working with Angular, I encountered an issue when trying to create a new component. The error message reads "Specify the generator name (e.g., nx generate @nrwl/workspace:library)" after exec ...

Incorporate TypeScript into your React projects for improved type

Currently, I am immersing myself in learning React with Typescript. One of the challenges I am facing is related to a specific view I have created. index.tsx import React from 'react' import { CButton } from '@coreui/react' import { us ...