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

Adding Vuetify to a Vue web component, then proceed to pass props to enhance its functionality

Currently working on developing a web component with Vue and using vuetify component library. The goal is to export it as a web component, but facing difficulties when trying to pass props to the exported component in the index.html file. Following the ste ...

Alter the top property of CSS using JavaScript

Hey there! I'm currently working on a project where I want to gradually change the background when a button is clicked on my website. Below you'll find snippets of JavaScript and HTML code that I'm using for this purpose. Can you take a look ...

Angular Recursive and Nested Reactive Form: Ensuring Continuous Validity, Even in Challenging Situations

Currently, I am in the process of developing a recursive Reactive Form using Angular. You can find the working form on STACKBLITZ HERE The functionality of the form is excellent as expected. However, due to its recursive and dynamic nature, where users ca ...

Ways to extract a value from an object with no properties using jQuery

In order to perform statistical calculations like Averages (Mean, Median, Mode) on data extracted from Datatables, I need the automatic calculation to remain accurate even when the table is filtered. While I have managed to obtain the desired values, extra ...

Improving the utilization of services in Angular

I have a DatesService that handles date manipulation. Additionally, I have two services that require date manipulation - EventsService and CalendarService. The CalendarService utilizes the EventsService. My query is: what would be more efficient (in terms ...

Clicking on a row in the Gridview should trigger the expansion or collapse of the Nested

My current issue involves a nested GridView setup like this: <asp:GridView ID="gvParent" runat="server" DataKeyNames="id"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:GridView ID="gv ...

Developing dynamic progress indicators in Django - A guide

I'm in the process of figuring out how to create a real-time progress bar for updating. The idea is that the server will update the user periodically on the current progress. Fortunately, I am familiar with making an Ajax call using Django and jQuery ...

Struggling to fix errors within a nested div element?

I'm currently utilizing AngularJS to perform basic form validation. Below is the current code snippet: <form name="myForm" id="form_id" method="post" novalidate> <div class="form-group"> <label for="myField_input" class="c ...

I am currently leveraging Angular 17, but I have yet to enable Vite. Can anyone guide me on

Despite having the most recent version of NX and Angular, my app has not yet integrated Vite. I've come across online suggestions on how to enable it, but none of them make sense to me because my project doesn't have an angular.json file. Instead ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

Step-by-step guide on retrieving data from E-goi with REST API in Google Apps Script

Looking to extract data from the e-goi API, I found a .jar file in their documentation. Unfortunately, there are no examples provided for the REST API, leaving me unsure of how to access it directly. As I'm still new to programs like this, I could rea ...

Is async programming synonymous with multi-threading?

Discussing a JavaScript code that utilizes the setInterval function every 2 seconds. There is also an animation event for some control triggered by the onblur event. If the onblur event occurs (along with the animation), there is a possibility of encount ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

A variety of negative () DOM Selectors

I've been trying to select a specific node using two not clauses, but so far I haven't had any luck. What I'm attempting to achieve is selecting an element whose div contains the string 0008, but it's not 10008 and also does not contain ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...