,

Angular Charts: Using Chart.js and JSON Server REST API | A Comprehensive Angular 14 Full Course

Posted by


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!

0 0 votes
Article Rating
19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Apurv Tripathi
7 months ago

Trying with your code, only getting 2 charts (bubble & scatter only) !!

Rivero Armando
7 months ago

Hi, I'm from Argentina and I really appreciate the video and sharing your knowledge.

James Ngige
7 months ago

This is amazing man, effortless and perfect. Good job

Enrique Ruiz
7 months ago

WOW!!! 👻

ismail görünmek
7 months ago

baby and rooster sounds in the background have an effect. nice and nice explanation 🙂 thanks

Shubham
7 months ago

Line chart???

Ben Jack
7 months ago

how to remove a grid in the chart?

Rodrigue Bazie
7 months ago

please Sir, i have a problem with my chart.js, my graph are without color , it is gray, please help me

Arshad Khan
7 months ago

Thanks Mann!!

nerdiloo
7 months ago

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.

Alvaro Bernabey
7 months ago

i love you bro thanks for anythings tkm

Josh sparrow
7 months ago

Thanks 🙏

Ndi Arfandi Hanutama
7 months ago

Failed to create chart: can't acquire context from the given item. How ?

Liyana Shirin
7 months ago

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.

Krish Bala
7 months ago

Hi, GM. Could pls give contact email / WhatsApp number, have question with screen shot to share for doubt. Thanks & Regards

hafeez badure
7 months ago

Thank You so much sir

gladis xavier
7 months ago

Please make one video regarding Multi Step Form with Step Progress Bar in angular bro

MUHAMMED FAISAN
7 months ago

Sir how to update image using api in angular

Marghubur Rahman Ansari
7 months ago

Please make video on full calendar which include add, edit events also in angular without using angular material