How to Dynamically Add Series to Angular Chart Component?
You can dynamically generate chart series in the Angular Chart component by inspecting your data model at runtime. This approach is ideal when the number of series is not fixed and depends on the structure of your data.
How It Works
getSeriesNames
This function inspects the first item in your data array and identifies all keys that begin with “y” (e.g., y, y1, y2, …). These keys represent the individual data fields for each chart series. It dynamically determines how many series should be rendered based on the structure of the data.
getYNameAndSeriesName
Given an index, this function returns:
- yName: The actual data field name used for plotting (e.g., y, y1, y2, …).
- name: A user-friendly label for the chart legend (e.g., Values 0, Values 1, …).
This mapping ensures that each series is correctly labeled and linked to its corresponding data field.
Template Loop
Using Angular’s *ngFor directive, the template dynamically loops through the series names returned by getSeriesNames. For each entry, it creates an
Code Example
app.component.html
<ejs-chart #chart style="display:block;" [chartArea]="chartArea" [width]="width" align="center" id="chartcontainer" [primaryXAxis]="primaryXAxis"
[primaryYAxis]="primaryYAxis" [title]="title" [tooltip]="tooltip" (load)="load($event)" [legendSettings]="legend">
<e-series-collection>
<ng-container *ngFor="let series of getSeriesNames(data[0]); let i = index">
<e-series [dataSource]="data" type="StackingColumn" xName="x" [yName]="getYNameAndSeriesName(i).yName" [name]="getYNameAndSeriesName(i).name"
[width]="2" [marker]="marker" columnSpacing="0.1" tooltipMappingName="MappingName"></e-series>
</ng-container>
</e-series-collection>
</ejs-chart>
app.component.ts
public getSeriesNames(dataItem: any): string[] {
const seriesNames = [];
for (const key in dataItem) {
if (key.startsWith('y')) {
seriesNames.push(key);
}
}
return seriesNames;
}
public getYNameAndSeriesName(index: number): { yName: string; name: string } {
const yName = index !== 0 ? `y${index}` : 'y';
const name = `Values ${index}`;
return { yName, name };
}
Output
Live Sample
Conclusion
I hope you enjoyed learning about how to dynamically Add series to Angular Chart Component.
You can refer to our Angular Chart’s feature tour page to learn about its other groundbreaking feature representations. You can also explore our Angular Chart Documentation to understand how to present and manipulate data.
For current customers, you can check out our Angular components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to explore our Angular Chart and other Angular components.
If you have any queries or require clarifications, please let us know in the comments below. You can also contact us through our support forums, Direct-Trac or feedback portal, or the feedback portal. We are always happy to assist you!