How to implement Chart.js in Angular
How to implement Chart.js in Angular
20 April 2021
Chart.js is an open source JavaScript library that makes it easy to include charts in your website. The charts are animated and responsive so we can show it on any device. If you want to combine Chart.js with Angular then we can use: ng2-chart. Adding this package gives you access to angular instructions so that you can use the Chart.js library.
Installation
To create a chart, we must immediately create a chart class. To do this, we have to pass a node, jQuery instance, or 2d reference on the canvas where we want to draw the chart. Here’s an example.
You can implement the chart in a simple way with the following instructions:
- If you do not have an existing project then create a new project with angular-cli.
ng new example-chartjs
- Install Chart.js in your Angular project
npm install chart.js --save
- Import Chart into its component
import Chart from 'chart.js';
- Use Chart in your html file and component file.
In your html file
In your component file:
The component should look similar to the following:
Adding Bootstrap
On this we are going to use some CSS classes of bootstrap, so we have to install bootstrap before that by using the following command.
$ npm install bootstrap
Also be sure to add the following line of code to the styles to include Bootstrap’s CSS file.
@import '~bootstrap/dist/css/bootstrap.min.css';
Importing ChartsModule
We need to import the ChartsModule so that we can use ng2-chart directives in our angular application. We can add the following line on the app.module.ts file to import the ChartsModule.
Also make sure to add ChartsModule to the import array of @NgModule decorator:
Adding Basic HTML Structure
Let’s add a base HTML structure (including tab navigation) to app.component.html:
Conclusion
That’s it, we just implemented the chart js library in our angular project by using the ng2-charts package and created various types of charts like line, bar, pie, doughnut, etc. We can easily represent simple data in graphical UI charts using chartJs. You can get more information in the official Chart.js and ng2-charts documentation.