codenamezero
codenamezero

Reputation: 3079

How to dynamically addEvent to Highcharts series with multiple charts?

I have my own Angular component that wraps a Highcharts, it works fine when I have only 1 chart if I addEvent on the Highcharts.Series, but it doesn't really work if I have multiple charts in the same component. I've tried the followings, but unable to addEvent to the specific chart's Series.

import * as Highcharts from 'highcharts';
import { chart, setOptions, addEvent } from 'highcharts'
export class MyHighchartsComponent {

  private chart: Highcharts.Chart;

  @ViewChild('highchart', { read: ElementRef }) chartElm: ElementRef;

  constructor() { }

  ngAfterViewInit() {
    const nativeElm = this.chartElm.nativeElement;
    chart(nativeElm, options, (chartObject) => {
      this.chart = chartObject;
      // not working
      // addEvent(chartObject.series, 'click', ...);
    });


    // works, but if i have multiple charts, the click is fired on all charts
    addEvent(Highcharts.Series, 'click', ...);

    // works, but it fires everywhere, i need it from the series only
    addEvent(nativeElm, 'click', ...);

  }
}

What is the way to do it?

Upvotes: 2

Views: 1876

Answers (1)

ppotaczek
ppotaczek

Reputation: 39139

You can add an event on a specific series:

Highcharts.addEvent(chart.series[0], 'click', function() {
    console.log(this.name);
});

Live demo: http://jsfiddle.net/BlackLabel/w7Lo3af9/


Or add it to the all series with some condition in the event function:

Highcharts.addEvent(Highcharts.Series, 'click', function() {
    if (this.options.id !== 'specialSeries') {
        return false;
    }

    console.log(this.name);
});

Live demo: http://jsfiddle.net/BlackLabel/pyq5bzma/

Upvotes: 3

Related Questions