Search code examples
javascriptamcharts4

AMCharts Clustered column chart - series name onclick event


I'm working on a clustered column chart in AMCharts 4. The chart has 3 series and that all work nicely.

I want to set up an on-click event to pull the series name and the index to be passed on later to @Controller in a Spring Boot App that will display more details to the clicked set of data.

I've managed to get the event listener to work on each series part to give the index details but I'm struggling with pulling the series name(trying to avoid separate API endpoint calls per series and rather pass the series name as a parameter).

 var series = chart.series.push(new am4charts.ColumnSeries())
    series.columns.template.tooltipText = "Result: {name}\nDate: {categoryX}\n#: {valueY}";
    series.dataFields.valueY = 'overall_findings'
    series.dataFields.categoryX = 'date'
    series.dataFields.index=40
    series.name = 'No Findings'
    series.columns.template.fill = am4core.color("#79DE79");
    series.columns.template.stroke = am4core.color("#d2d287");
    series.columns.template.events.on("hit", function(ev) {
        console.log("clicked on ", ev.target.dataItem.name);
        console.log("clicked on ", ev.target.dataItem.categoryX);
    }, this);

Tried to override/assign all sorts of dataItem values per series to see if I can use any to pull this information with no luck. Funny thing is that when setting up the tooltip above I'm able to pass this value as 'name' - tried also with series.columns.* fields

series.columns.template.tooltipText = "Result: {name}\nDate: {categoryX}\n#: {valueY}";

Does anyone have some ideas when to look for this value in the event?

Regards, Jarek.


Solution

  • The associated series can be obtained through the component property in the dataItem.

    seriesName = ev.target.dataItem.component.name;
    

    As for index, if you're looking for the index of the series, you can use the indexOf property on the chart's series list. You can access the chart object through the baseSprite property:

    seriesIndex = ev.target.baseSprite.series.indexOf(ev.target.dataItem.component)
    

    If you're looking for the index of the data item associated with the column, call indexOf on the series' dataItems list:

    dataItemIndex = ev.target.dataItem.component.dataItems.indexOf(ev.target.dataItem);