JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

How to Create a Pie Chart in Angular

Getting started with data visualization in Angular

Mwiza Kumwenda
JavaScript in Plain English
4 min readFeb 25, 2021

--

Photo by Adeolu Eletu on Unsplash

Data is the gold of the 21st century, but for data to be meaningful, it has to be well presented for the user to make sense of it. Graphs and charts are one of the best ways of making data presentable.

In this guide, we will take a look at how to present your data to users using a pie chart in Angular. We will do so, with the help of the ng2charts library.

The ng2charts library is based on the famous visualization library: chart.js. However, unlike chart.js that is geared towards vanilla JavaScript, ng2charts is specifically made for Angular and is, therefore, easier to implement and work with when you are using the Angular framework.

Getting started

We will start off by creating a new project in Angular, using the Angular CLI. I will name my project pie-chart. Simply, run the command below to create the new project.

$ ng new pie-chart --defaults

Adding dependencies to the project

Before we proceed to create the pie-chart. We will need to add three dependencies in the form of npm packages that are required for plotting our chart. The npm packages that we will install are ng2-charts, chart.js, and chartjs-plugin-datalabels.

We will install all three dependencies with one single command below. Make sure you run the command in your applications’ root folder.

$ npm install ng2-charts chart.js chartjs-plugin-datalabels --save

Update the main module file

Once you have installed the required packages above, you need to import ChartsModule from ng2charts in your main module file. In this case, the app.module.ts file.

In addition to importing the ChartsModule, add the ChartsModule to the array of imported modules.

Your app.module.ts file should now look as below. The only code that has been added is the one in bold.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ChartsModule

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Responses (1)

Write a response