Charts in Angular with JSON Server REST API | Angular Charts using Chart.js | Angular 14 Full Course
If you are looking to build dynamic and interactive charts in your Angular applications, you’ve come to the right place. In this article, we will explore how to integrate chart.js, a popular JavaScript library, with Angular to create stunning charts that are data-driven.
Before we dive into the details, let’s quickly touch upon the fundamentals. Angular is a widely-used framework for building web applications. It provides a powerful set of tools and features that enable developers to create robust and performant applications. On the other hand, chart.js is a flexible and lightweight library that allows you to create various types of charts, such as line charts, bar charts, pie charts, and more, using HTML5 canvas.
Setting up the Environment
To get started with creating charts in Angular, we need to set up our development environment. Assuming you have Angular CLI installed, run the following command to create a new Angular project:
ng new angular-charts-project
Next, navigate into the project folder:
cd angular-charts-project
To use chart.js in our project, we need to install it as a dependency. Run the following command to install chart.js:
npm install chart.js
Great! With the project and dependencies set up, we can now proceed to create our charts in Angular.
Fetching Data from JSON Server REST API
To make our charts dynamic and data-driven, we will fetch data from a REST API. In this example, we will use JSON Server, a simple fake REST API that allows us to make HTTP requests and simulate a server’s behavior. Start by installing JSON Server globally by running the following command:
npm install -g json-server
Once installed, create a new JSON file, let’s say data.json
, and populate it with some sample data. For instance, we can create an array of objects, each representing a data point for our chart. Make sure to include fields such as labels and values that are relevant to your chart’s type.
After creating the JSON file, start the JSON server by running the following command:
json-server --watch data.json
This will start a local server on http://localhost:3000
, serving the data from data.json
. Now, we can make HTTP requests to this server to fetch the data for our charts.
Implementing the Chart Component
In Angular, we can create a separate component to house our chart. Let’s call it chart.component.ts
. Inside this component, we can define a method to fetch the data from the JSON server using Angular’s HttpClientModule. Here is an example of how this method can be implemented:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
chartData: any = {};
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.fetchChartData();
}
fetchChartData(): void {
this.http.get('http://localhost:3000/chart-data').subscribe(data => {
this.chartData = data;
// Call a method to render the chart here
});
}
}
In the fetchChartData
method, we make an HTTP GET request to the /chart-data
endpoint on our JSON server. Upon receiving the response, we assign it to the chartData
property of our component. You can replace the URL with the relevant endpoint in your REST API. Now, we can use this data to render the chart using chart.js.
Rendering the Chart
To render the chart, we need to create a canvas element in our chart.component.html
template. We can use the ngAfterViewInit
lifecycle hook to ensure that the canvas is available before we attempt to render the chart. Here is an example of how the template can be structured:
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>
Next, modify the ChartComponent
to include the necessary code for rendering the chart. You can access the canvas element using document.getElementById('myChart')
or by using Angular’s @ViewChild
decorator. Once you retrieve the canvas element, you can create a new instance of chart.js and pass in the chart data that we fetched earlier. Here is an example of how the updated component can look like:
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Chart } from 'chart.js';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit, AfterViewInit {
chartData: any = {};
@ViewChild('myChart', {static: true}) chartCanvas: ElementRef;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.fetchChartData();
}
ngAfterViewInit(): void {
this.renderChart();
}
fetchChartData(): void {
this.http.get('http://localhost:3000/chart-data').subscribe(data => {
this.chartData = data;
});
}
renderChart(): void {
const ctx = this.chartCanvas.nativeElement.getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: this.chartData.labels,
datasets: [
{
label: 'Chart Data',
data: this.chartData.values,
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}
]
},
options: {
responsive: true
}
});
}
}
In the renderChart
method, we use the retrieved canvas element to create a new instance of chart.js. We specify the chart type, labels, values, and other options required to customize the chart. You can explore the chart.js documentation to learn about the various chart configurations and options available.
Conclusion
Congratulations! You have successfully integrated chart.js with Angular to create dynamic and interactive charts. By fetching data from a JSON server REST API and incorporating it into chart.js, you can create visually appealing charts that are data-driven. Feel free to explore different chart types, customize their appearance, and experiment with various data sources to enhance your charting capabilities further.
Remember to regularly practice and explore the various features and possibilities offered by Angular and chart.js. The more you experiment and push the boundaries of what you can achieve, the more proficient and skilled you will become.
Keep coding, keep learning!
Trying with your code, only getting 2 charts (bubble & scatter only) !!
Hi, I'm from Argentina and I really appreciate the video and sharing your knowledge.
This is amazing man, effortless and perfect. Good job
WOW!!! 👻
baby and rooster sounds in the background have an effect. nice and nice explanation 🙂 thanks
Line chart???
how to remove a grid in the chart?
please Sir, i have a problem with my chart.js, my graph are without color , it is gray, please help me
Thanks Mann!!
Very nice. Has anyone tried making a clickable bar chart (i.e. you click a bar it takes you to page A, click another it takes you to page B etc.) in Angular? I've tried based on their API section of the docs but get the "Cannot read properties of undefined (reading 'getElementsAtEventForMode')". Thanks.
Update: figured it out. I was using 'this' in an anonymous function instead of the fat arrow => , so 'this' was the wrong context. All good.
i love you bro thanks for anythings tkm
Thanks 🙏
Failed to create chart: can't acquire context from the given item. How ?
Hi Sir, I am trying to get the ngx line chart to get data from api. I am using Angular 13 and spring boot for backend. Is there any example i can follow.
Hi, GM. Could pls give contact email / WhatsApp number, have question with screen shot to share for doubt. Thanks & Regards
Thank You so much sir
Please make one video regarding Multi Step Form with Step Progress Bar in angular bro
Sir how to update image using api in angular
Please make video on full calendar which include add, edit events also in angular without using angular material