Search code examples
javascriptangularhighchartsangular-highcharts

Highcharts Angular Chart not redrwan from renderer.button event


In the chart, there are 2 custom buttons to update series to redraw the chart(toggle of views) by Percentage(%) or by count. In the callback function of the renderer.button, When I click count button I'm updating the series data by changing the value of y in the data object and calling chart.update() method with modified series data

const seriesData: any = this.data;
this.update(seriesData, true);
this.redraw();

Chart is not redrawn automatically it's redrawn only if I zoom in or zoom out the browser or any other actions. What is the missing part here.

enter image description here

Stackblitz


Solution

  • The problem which you are struggling to is that calling an update method in the render function creates an infinity loop.

    Render calls update -> updated redraws chart -> render is calling again -> render calls update -> ...

    One of the methods to avoid that is to use some boolean 'flags' to control that update will be called once.

    Simple demo with console.log to test the flow: https://jsfiddle.net/BlackLabel/acoxmhdw/

    let chartForUpdate = true;
    
    Highcharts.chart('container', {
    
      chart: {
        events: {
          render() {
            let chart = this;
                    console.log('test redraw call 1')
            if (chartForUpdate) {
              chartForUpdate = false;
              chart.series[0].update({
                data: [5, 10]
              })
              console.log('test condition IF call')
            }
            console.log('test redraw call 2')
                    chartForUpdate = true
          }
        }
      },
    
      series: [{
        data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
      }]
    });
    

    EDIT

    I made a mistake, my apologize - the maximum call stack wasn't occurred because of the infinity loop from render calls, but from the data which you had tried to paste.

    Updated data must be in the format which is required by Highcharts - that is a series configuration object with data as array of objects or array of values or array of arrays - documentation: https://www.highcharts.com/docs/chart-concepts/series and https://api.highcharts.com/class-reference/Highcharts.Series#update

    Meanwhile, in your demo the array of the data objects is passing to the update function which creates an error.

    I am not sure which values you would like to display after triggering this button, but you will need to create a new series object for it. Something like this:

    https://stackblitz.com/edit/angular-9nkrgd-aykarp?file=src/app/app.component.ts