Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below:

events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },


  public openDialog(option,type){
       //Do Something
  }

EDIT

Check out this helpful link discussing binding this with functions.

Could there be something crucial that you're overlooking?

Answer №1

Ensure to update the code by replacing arrow functions with regular functions.

In the updated code, the assignment of chart options has been moved inside a function called init(){}, where var that = this; is declared. Additionally, the arrow function syntax ()=>{} has been replaced with function().

You can view the updated stackblitz demo Here

import {  Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import { Chart } from 'angular-highcharts';
import { HighchartsService } from './highcharts.service.ts'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('charts') public chartEl: ElementRef;
  myOptions={};
  constructor(private highcharts: HighchartsService) { }
  ngOnInit(){
    this.init();
    this.highcharts.createChart(this.chartEl.nativeElement, this.myOptions);
  }
  init(){
   var that = this;
   this.myOptions = {
    chart: {
      type: 'bar',
      events: {
      load: function(){
      var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>that.openDialog()
            );
            }
          })(i)
        }
      }
      }
    },
    },
    title: {
      text: 'Stacked bar chart'
    },
    xAxis: {
      categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
      min: 0,
      title: {
        text: 'Total fruit consumption'
      }
    },
    legend: {
      reversed: true
    },
    plotOptions: {
      series: {
        stacking: 'normal'
      }
    },
    series: [{
      name: 'John',
      data: [5, 3, 4, 7, 2]
    }, {
      name: 'Jane',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Joe',
      data: [3, 4, 4, 2, 5]
    }]
  };
      }

  public openDialog(){
       console.log('open dialog, hey this works here')
  }
}

Answer №2

I am uncertain of the success of this method, but as far as I can tell, your current code is not properly referencing the myOptions object and its series key.

To resolve this issue, move the declaration of series outside of the myOptions object.

seriesData = [{
  name: 'John',
  data: [5, 3, 4, 7, 2]
}, {
  name: 'Jane',
  data: [2, 2, 3, 2, 1]
}, {
  name: 'Joe',
  data: [3, 4, 4, 2, 5]
}];

myOptions = {
    chart: {
        type: 'bar',
        events: {
           load: () => {
              for (var j in this.seriesData) {
                  var series = this.seriesData[j];
                  for (var i in series.data) {
                   .
                   .
                  }
              }
            }
        }
    },

    series: this.seriesData
}

Answer №3

After making a simple change, I finally managed to get it to work.

events: {
  load: function(e) {
   var chart : any = e.target; // accessing the chart details
  for (var j in chart.series) {
    console.log(j)
    var series = chart.series[j];
    for (var i in series.data) {

      ((i) =>{
        console.log(i)
        var point = series.data[i];
        if (point.graphic) {
          point.graphic.on('click',(e)=>this.openDialog()
        );
        }
      })(i)
    }
  }
  }.bind(this) //binding this to access openDialog function
},


public openDialog(option,type){
   //Do Something
}

In order to make it work, I had to bind 'this' since it was not coming directly from the chart. By using '.bint(this)' within the load function and accessing the chart details using 'e.target', I was able to successfully resolve the issue.

Check out the Stackblitz Demo for reference.

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

Enhance user experience by implementing an autocomplete feature for a text input field

Can you name the process in which a form is automatically filled using database information without needing to refresh the page? One common example of this technique is seen on platforms like Google or Facebook, where they predict friends you may be searc ...

What is the optimal order for executing JavaScript, jQuery, CSS, and other controls to render an HTML page efficiently?

What are some recommended strategies for optimizing webpage loading speed? What key factors should be taken into consideration? ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

IE does not support hover effects

Having trouble with a hover effect that works in Chrome but not in MSIE. Are there any alternatives or fixes to make it work in MSIE? The hover/rollover effects I've tried all seem to have this issue in IE. normalize.css demo.css set2.css font- ...

Error: The argument provided is of type 'unknown', which cannot be assigned to a parameter of type 'string'. This issue arose when attempting to utilize JSON.parse in a TypeScript implementation

I'm currently converting this code from Node.js to TypeScript and encountering the following issue const Path:string = "../PathtoJson.json"; export class ClassName { name:string; constructor(name:string) { this.name = name; } ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

When the keyboard appears, the Ionic 2 form smoothly slides upwards

I am currently working with the most recent version of Ionic 2. In my code, I have a <ion-content padding><form></form></ion-content> containing a text input. However, when attempting to enter text on an Android device, the keyboard ...

Retrieving JSON information from a PHP script with AJAX

I am currently experiencing an issue with my PHP script, 'getNews.php'. Despite working correctly in the terminal and returning the expected data, I am encountering difficulties when trying to retrieve this information through JavaScript. <?p ...

What could be the reason behind the for loop not running within a typescript function?

My confusion lies in the for loop within this function that seems to never run. Each console log is set up to return a specific value, but the looping action doesn't trigger. Can someone provide insight into what might be causing this issue? export fu ...

When using Jest, the mongoose findOneAndUpdate function may return null values for both error and document

I've been struggling with Mongoose's findOneAndUpdate method as it doesn't seem to provide any useful information. I have tried accessing the Query returned from calling it (stored in updatedUser), but all it returns is null. Adding a callba ...

Having trouble integrating MaterialUI Datepicker, Dayjs, useFormik, and Yup

Currently, I am facing a recurring issue with the Material UI Date picker in conjunction with day js. The problem arises when I select a date on the calendar for the first time, it updates correctly in the text field but fails to work thereafter. Additiona ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...

Incorporate the Google Maps API into a React application

I've recently started learning react and I'm currently trying to integrate the Google Maps API into my React application. Within my app, I have a search input field and a designated area for the map located at http://localhost:8080/. My main qu ...

Having trouble getting TypeScript to install using npm on a Mac?

My goal is to use Typescript as a local dependency by checking it into my devDependencies and using it via an npm script after installing it with 'npm install'. However, when I try this on my machine, I find that Typescript (and webpack-cli as w ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

What is the process for obtaining the final element in an array of objects when a particular character is present in the value of a key?

Given the following array: arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherTh ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

What are the steps to launching a yarn app on a dev server?

I've always stuck with npm and never ventured into using yarn or webpack explicitly. The code from this repository needs to be executed: https://github.com/looker-open-source/custom_visualizations_v2 I'm looking for a way to run it like a develo ...