How to Create Charts in Angular With Dynamic Data Using Chart.js

Display dynamic data in simple bar, line, pie, and doughnut charts using the Chart.js library and Angular

Nipuni Premadasa
Bits and Pieces

--

Hello readers😍!

In this article, I will describe how to display dynamic data in simple bar, line, pie, and doughnut charts using the Chart.js library and Angular.

What is Chart.js?

Chart.js is an open-source JavaScript library that is very popular among JavaScript developers. It provides a wide range of chart types, plugins, and customization options. Chart.js is highly customizable with custom plugins to create annotations, zoom, or drag-and-drop functionalities to name a few things. Chart.js is compatible with all popular JavaScript frameworks such as React, Angular, and Vue. Also, it has good documentation, API reference, and examples.

Cool!😎 Let’s start developing the app.

👉Check out some Angular dev tools you could use in 2023

  1. How to install Angular CLI

First, we need to install a command line interface tool called Angular CLI. It is useful for initializing and developing angular applications.

npm install -g @angular/cli

2. How to create a new Angular application

In the terminal execute the following command to create a new Angular application.

ng new angular-charts

To start the local development server, navigate to the project folder and execute the following command in the terminal.

cd angular-chart
ng serve

The Angular application will run on HTTP://localhost:4200/

Next, we have to install the Chart.js library to your application using the following command.

npm install chart.js

As the next step, I created the chart-base component as the parent component that contains common functionalities of the chart component. We can create it easily using the following command. It will create the charts folder inside the app folder and create the chart-base component inside the charts folder.

ng generate component charts/chart-base

Here I’m creating additional four components inside the chart folder for each chart.

ng generate component charts/bar-chart
ng generate component charts/line-chart
ng generate component charts/pie-chart
ng generate component charts/doughnut-chart

3. How to create the JSON server

Since I’m not using a backend and a database, I have used a JSON server to get the moc data. Now we can open a new terminal and give the following command to install a JSON server.

npm install -g json-server

We can create a JSON file inside the root folder in our project. Here I have created the chart-data.json file with the following sample data.

We can run the JSON server with the following command. It will be running on port 3000. ( http://localhost:3000)

json-server --watch chart-data.json

4. How to create a service

As the next step, I have created a service to encapsulate the code that handles fetching data from the JSON server. We can create it by executing the following command in the terminal.

ng generate service charts/chart

Then I imported HttpClient in the charts.service.ts and injected it via the service constructor.

Next, I have defined the getChartInfo() method for sending the GET request to the server for fetching data. Here I call the get() method of HttpClient to send a GET request to the JSON server.

5. How to display data

Here I have to open all four component.html files (bar-chart.component.html, line-chart.component.html, pie-chart.component.html, and doughnut-chart.component.html) and paste the following code.

In the above code, I have created a container called chart-container that is contained canvas with the Id of “Chart”. Here Angular’s string interpolation is used to render the “chart” variable, which will create inside the chart-base.component.ts. When we are using Chart.js, canvas size changes cannot be done directly from the canvas element. Therefore, the parent container can be used to update the canvas render and display size by setting the relative value for the container size.

6. How to implement code in chart-base.component.ts

Here, I’m going to use the getChartInfo() method in the component. For that, first I need to inject the created service (ChartsService) into the component and access the method as shown below.

In the above code, I have injected the service in the constructor then called the getChartInfo()method and subscribed to it. When getting the response from the subscribe method, it will be an array of objects containing year, amount, and colorcode.

I have declared the property as chartInfo and assigned the response that was received from the subscriber. Then I have declared three arrays named labeldata, realdata, and colordata and added retrieved values for them using a for loop.

In addition to ngOnInit() there is a placeholder for createChart() method in ChartBaseComponent. The createChart() method is called inside the ngOnInit() by passing three arguments.

7. How to create charts

Here, BarChartComponent, LineChartComponent, PieChartComponent, and DoughnutChartComponet classes extend the BaseChartComponent and provide their own implementation of the createChart() method specific to the type of chart they represent. The createChart() is overridden by the method to create a relevant chart using the Chart.js library. Each class has its own constructor that injects the ChartService and calls the super constructor of the base class.

Inside the createChart() method I have provided the type of chart, the labels, and the data. Here only the type varies from component to component.

Now, let’s go through each component related to chart types one by one.

💡 Pro Tip: If you end up needing to use these chart components over and over for multiple projects, consider using an open-source component-management hub like Bit to extract these components out of your codebase and reuse them across multiple projects using a simple command.

Learn more here:

a) Bar chart

Bar chart

b) Line chart

Line chart

c) Pie chart

Pie chart

d) Doughnut chart

Doughnut chart

Conclusion

In conclusion, this article demonstrated how to create dynamic bar, line, pie, and doughnut charts in an Angular application using the Chart.js library. By following the steps outlined in the article, developers can easily set up an Angular project, install the necessary dependencies, create the required components, and integrate the Chart.js library. The article also covered the process of fetching data from a JSON server using a service and dynamically displaying the retrieved data in the charts. With the flexibility and extensive customization options offered by Chart.js, developers can create visually appealing and interactive charts to represent their data in Angular applications. By leveraging the power of Chart.js and Angular, developers can enhance their data visualization capabilities and provide valuable insights to users.

You can find the complete source code here. https://github.com/NipuniPremadasa/chartjs-angular-demo.git

Try this code yourself and enjoy the output.

We have reached the end of the article and I hope you got something useful from this article.😃 Thanks for reading❤️!

Build Angular Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--

Undergraduate at Faculty of Information Technology, University of Moratuwa | Former Trainee Software Engineer at Embla Software Innovation(PVT) Ltd., Sri Lanka