This tutorial will show you every step you need to use amCharts 4 with Angular.
Using amCharts in Angular
VERSION INFO This tutorial deals with Angular2 or later. If you are using AngularJS 1.x, please refer to this tutorial instead.
IMPORTANT amCharts 4 requires TypeScript 2.9 or later. Using any older version will result in error.
First, create a new Angular project:
npx -p @angular/cli ng new my-project cd my-project
Edit the package.json
and add --prod --build-optimizer=false
to the "build"
script:
"scripts": { ... "build": "ng build --prod --build-optimizer=false", ... },
(See "Build optimizer" section for more information)
You can now run your project by using this command:
npm start
If you load http://localhost:4200/
in a browser, you should see your new project!
Now it's time to add in an amCharts 4 chart. First create a new chart component:
npm run -- ng generate component chart --module app
Then use this command to install amCharts 4:
npm install @amcharts/amcharts4
Then add in the following code to the src/app/chart/chart.component.html
file:
<div id="chartdiv" style="width: 100%; height: 500px"></div>
And use the following code in src/app/chart/chart.component.ts
:
import { Component, Inject, NgZone, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; // amCharts imports import * as am4core from '@amcharts/amcharts4/core'; import * as am4charts from '@amcharts/amcharts4/charts'; import am4themes_animated from '@amcharts/amcharts4/themes/animated'; @Component({ selector: 'app-chart', templateUrl: './chart.component.html', styleUrls: ['./chart.component.css'] }) export class ChartComponent { private chart: am4charts.XYChart; constructor(@Inject(PLATFORM_ID) private platformId, private zone: NgZone) {} // Run the function only in the browser browserOnly(f: () => void) { if (isPlatformBrowser(this.platformId)) { this.zone.runOutsideAngular(() => { f(); }); } } ngAfterViewInit() { // Chart code goes in here this.browserOnly(() => { am4core.useTheme(am4themes_animated); let chart = am4core.create("chartdiv", am4charts.XYChart); chart.paddingRight = 20; let data = []; let visits = 10; for (let i = 1; i < 366; i++) { visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10); data.push({ date: new Date(2018, 0, i), name: "name" + i, value: visits }); } chart.data = data; let dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.grid.template.location = 0; let valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); valueAxis.tooltip.disabled = true; valueAxis.renderer.minWidth = 35; let series = chart.series.push(new am4charts.LineSeries()); series.dataFields.dateX = "date"; series.dataFields.valueY = "value"; series.tooltipText = "{valueY.value}"; chart.cursor = new am4charts.XYCursor(); let scrollbarX = new am4charts.XYChartScrollbar(); scrollbarX.series.push(series); chart.scrollbarX = scrollbarX; this.chart = chart; }); } ngOnDestroy() { // Clean up chart when the component is removed this.browserOnly(() => { if (this.chart) { this.chart.dispose(); } }); } }
The chart code goes inside the ngAfterViewInit
method.
Lastly, add <app-chart></app-chart>
to your src/app.component.html
file.
Now you can run npm start
again and you should see a chart.
IMPORTANT Currently amCharts 4 does not fully support TypeScript's strict mode. Please click here for more details.
Polyfills
IMPORTANT If you want to support older browsers, make sure you set up polyfills. Click here for detailed instructions.
Lazy loading amCharts
Check out this tutorial for information on how you can lazy-load amCharts modules on-demand, rather than compiling them into your app.
Fixing broken resizing on route
If you are using routing in your application you might see the issue of charts losing their auto-resize capabilities when transitioning between pages.
This happens because chart is using a resize sensor which gets knocked of its feet when chart container is moved about in a DOM tree.
The solution is to reset it when such routing occurs:
chart.svgContainer.resizeSensor.reset();
Warnings in Angular 10+
Angular 10+ gives warnings when using third party npm packages. This is a problem with Angular, not amCharts. The warnings do not affect the behavior, but you can disable them by adding allowedCommonJsDependencies
to your angular.json
file, like this:
"build": { "builder": "@angular-devkit/build-angular:browser", "options": { "allowedCommonJsDependencies": [ "core-js", "raf", "xlsx", "@babel/runtime" ] // ... } // ... },
Build Optimizer
Because Angular's build optimizer is designed for Angular apps, it often breaks with non-Angular code (such as amCharts).
This is a bug in Angular, so there isn't anything we can do about it. That's why we recommend using --build-optimizer=false
to disable the build optimizer.
However, sometimes you cannot disable the build optimizer, because it would increase your file size too much. In that case we recommend using our script version, which will load amCharts as global variables (which bypasses Angular).
You can use the following code to get correct static types:
declare const am4core: typeof import("@amcharts/amcharts4/core");
declare const am4charts: typeof import("@amcharts/amcharts4/charts");
declare const am4themes_animated: typeof import("@amcharts/amcharts4/themes/animated").default;
You can also import types by using import type
:
import type { XYChart } from "@amcharts/amcharts4/charts";
You must use import type
, because that guarantees that it will only import the types, not the code.