Category / Section
How to toggle series based on clicked legend in Angular Charts?
2 mins read
Description
This article explains how to dynamically toggle chart series visibility in Angular Charts by interacting with the legend. When a legend item is clicked, only the corresponding series is displayed, hiding the rest. Clicking the same legend again restores the chart to show all series.
Solution
Using the legendClick event, the chart can react to legend interactions by comparing the clicked item’s legendText and toggling the visibility of series accordingly.
Code Snippet
The following example shows how to toggle series based on clicked legend.
app.component.ts
public previousSelected = null;
public legendClick(args): void {
if (this.previousSelected === args.legendText)
{
for (let i = 0; i < args.chart.series.length; i++)
{
if (args.chart.series[i].name === this.previousSelected)
{
args.chart.series[i].visible = false;
}
else
{
args.chart.series[i].visible = true;
}
}
this.previousSelected = null;
}
else
{
for (let j = 0; j < args.chart.series.length; j++)
{
args.chart.series[j].visible = false;
}
this.previousSelected = args.legendText;
}
}
Output
The following screenshot illustrates the output of the above code snippet