Home » ng2 charts in Angular – Chart.js

ng2 charts in Angular – Chart.js

In this article, we can try to implement the charts in the angular application, Charts is one of the important parts of development example -analytical data.

There are multiple open-source libraries present in the market and ng2 charts in one of the famous among them. Ng2 charts is actively managed by valor-software.

By Using ng2 charts we can create Line, Bar, Pie, Doughnut, Radar, Polar charts. For the implementation of Ng2 charts, there is a dependency on Chart.js open-source javascript library. In the following tutorial, we can see how to implement ng2 charts in angular projects.

Step 1: Create a project for ng2 Charts

Open the terminal and just fire the below command to create the project

 ng new ng2chart

Step 2: Install the required packages

Please check the version of the packages, because not every package is compatible with your angular project version.

Fire the below commands to install the required packages

npm install chart.js@2.8.0 --save

npm i ng2-charts@2.2.5 --save

There is a dependency on the chart.js file so we have to install this.

How to Add Charts in Angular Code

Add ChartsModule in app.module.ts

import { ChartsModule } from 'ng2-charts';

// In your App's module:
imports: [
   ChartsModule
]

For demo purposes, I am going to make changes to the app.component.html file.

If you get any dependencies errors, please check those and install

For the Line chart, we need a plugin to install from the below command

npm i chartjs-plugin-annotation@0.5.7

Copy the code from Github repository ng2charts

It will show like below image

Bar Chart

For the Bar chart, we need a plugin to install from the below command

npm i chartjs-plugin-datalabels

Copy the code from Github repository ng2charts

The bar chart will show like below image

Note: Integration of ng2charts is very simple, but the important part is the version of npm packages is compatible with the angular project if all packages are installed correctly then it will work perfectly without any errors.

Need help?

Read this post again, if you have any confusion or else add your questions in Community