Using Chart.js in Angular With Example

Chart.js is a powerful and flexible JavaScript library for creating various types of charts. In this guide, we will walk through the steps to integrate Chart.js with Angular and create different types of charts using sample financial data.

Prerequisites

Before we start, ensure you have the following:

  • Node.js installed
  • Angular CLI installed

Step 1. Setting Up an Angular Project

If you don't have an existing Angular project, create a new one using Angular CLI:

ng new ng-chart
cd ng-chart

Step 2. Installing Chart.js

Install Chart.js via npm:

npm install chart.js

Step 3. Creating the Angular Component

Create a new component for displaying the charts:

ng generate component charts

Step 4. Importing Chart.js

In your charts.component.ts, import Chart.js:

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js/auto';

@Component({
  selector: 'app-charts',
  templateUrl: './charts.component.html',
  styleUrls: ['./charts.component.css']
})
export class ChartsComponent implements OnInit {
  chart: any = [];
  sampleData = [
    { hoseNo: 'H001', total_Receivable: 1000, total_Received: 700, due_Amount: 300, status: 'pending', last_Payment_Date: '2024-07-01', last_Payment_Days: 10 },
    { hoseNo: 'H002', total_Receivable: 1500, total_Received: 1500, due_Amount: 0, status: 'completed', last_Payment_Date: '2024-06-25', last_Payment_Days: 16 },
    { hoseNo: 'H003', total_Receivable: 1200, total_Received: 1000, due_Amount: 200, status: 'pending', last_Payment_Date: '2024-06-30', last_Payment_Days: 11 },
    { hoseNo: 'H004', total_Receivable: 1800, total_Received: 1800, due_Amount: 0, status: 'completed', last_Payment_Date: '2024-07-05', last_Payment_Days: 6 },
    { hoseNo: 'H005', total_Receivable: 1300, total_Received: 900, due_Amount: 400, status: 'pending', last_Payment_Date: '2024-07-02', last_Payment_Days: 9 }
  ];

  ngOnInit() {
    this.prepareCharts();
  }

  private prepareCharts() {
    this.initBarChart();
    this.initPieChart();
    this.initLineChart();
    this.initStackedBarChart();
    this.initHeatMapChart();
  }

  private initBarChart() {
    const ctx = document.getElementById('receivablesVsReceivedChart') as HTMLCanvasElement;
    const labels = this.sampleData.map(item => item.hoseNo);
    const receivableData = this.sampleData.map(item => item.total_Receivable);
    const receivedData = this.sampleData.map(item => item.total_Received);

    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [
          {
            label: 'Total Receivable',
            data: receivableData,
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderColor: 'rgba(75, 192, 192, 1)',
            borderWidth: 1
          },
          {
            label: 'Total Received',
            data: receivedData,
            backgroundColor: 'rgba(153, 102, 255, 0.2)',
            borderColor: 'rgba(153, 102, 255, 1)',
            borderWidth: 1
          }
        ]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  }

  private initPieChart() {
    const ctx = document.getElementById('paymentStatusChart') as HTMLCanvasElement;
    const pendingCount = this.sampleData.filter(item => item.status === 'pending').length;
    const completedCount = this.sampleData.filter(item => item.status === 'completed').length;

    new Chart(ctx, {
      type: 'pie',
      data: {
        labels: ['Pending', 'Completed'],
        datasets: [{
          data: [pendingCount, completedCount],
          backgroundColor: ['rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)'],
          borderColor: ['rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)'],
          borderWidth: 1
        }]
      }
    });
  }

  private initLineChart() {
    const ctx = document.getElementById('dueAmountOverTimeChart') as HTMLCanvasElement;
    const labels = this.sampleData.map(item => item.last_Payment_Date);
    const dueAmountData = this.sampleData.map(item => item.due_Amount);

    new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Due Amount',
          data: dueAmountData,
          backgroundColor: 'rgba(255, 159, 64, 0.2)',
          borderColor: 'rgba(255, 159, 64, 1)',
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  }

  private initStackedBarChart() {
    const ctx = document.getElementById('stackedBarChart') as HTMLCanvasElement;
    const labels = this.sampleData.map(item => item.hoseNo);
    const receivableData = this.sampleData.map(item => item.total_Receivable);
    const receivedData = this.sampleData.map(item => item.total_Received);
    const dueAmountData = this.sampleData.map(item => item.due_Amount);

    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [
          {
            label: 'Total Receivable',
            data: receivableData,
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderColor: 'rgba(75, 192, 192, 1)',
            borderWidth: 1
          },
          {
            label: 'Total Received',
            data: receivedData,
            backgroundColor: 'rgba(153, 102, 255, 0.2)',
            borderColor: 'rgba(153, 102, 255, 1)',
            borderWidth: 1
          },
          {
            label: 'Due Amount',
            data: dueAmountData,
            backgroundColor: 'rgba(255, 159, 64, 0.2)',
            borderColor: 'rgba(255, 159, 64, 1)',
            borderWidth: 1
          }
        ]
      },
      options: {
        scales: {
          x: {
            stacked: true
          },
          y: {
            stacked: true,
            beginAtZero: true
          }
        }
      }
    });
  }

  private initHeatMapChart() {
    const ctx = document.getElementById('heatMapChart') as HTMLCanvasElement;
    const labels = this.sampleData.map(item => item.hoseNo);
    const paymentDaysData = this.sampleData.map(item => item.last_Payment_Days);
    const colors = this.sampleData.map(item => {
      if (item.last_Payment_Days < 10) return 'rgba(75, 192, 192, 0.2)';
      if (item.last_Payment_Days < 20) return 'rgba(255, 205, 86, 0.2)';
      return 'rgba(255, 99, 132, 0.2)';
    });

    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: 'Days Since Last Payment',
          data: paymentDaysData,
          backgroundColor: colors,
          borderColor: colors.map(color => color.replace('0.2', '1')),
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  }
}

Step 5. Adding HTML Template

In your charts.component.html, add the HTML elements for the charts:

<div>
  <!-- Bar Chart: Receivables vs. Received Amounts -->
  <h2>Receivables vs. Received Amounts</h2>
  <canvas id="receivablesVsReceivedChart" width="400" height="200"></canvas>

  <!-- Pie Chart: Payment Status Distribution -->
  <h2>Payment Status Distribution</h2>
  <canvas id="paymentStatusChart" width="400" height="200"></canvas>

  <!-- Line Chart: Due Amount Over Time -->
  <h2>Due Amount Over Time</h2>
  <canvas id="dueAmountOverTimeChart" width="400" height="200"></canvas>

  <!-- Stacked Bar Chart: Comparison of Receivables, Received, and Due Amounts -->
  <h2>Comparison of Receivables, Received, and Due Amounts</h2>
  <canvas id="stackedBarChart" width="400" height="200"></canvas>

  <!-- Heat Map: Days Since Last Payment -->
  <h2>Days Since Last Payment (Heat Map)</h2>
  <canvas id="heatMapChart" width="400" height="200"></canvas>
</div>

Step 6. Adding Styles

In your charts.component.css, you can add styles to customize the appearance of your charts:

canvas {
  display: block;
  margin: 0 auto;
}

Step 7. Adding Charts to the App Component

Include the ChartsComponent in your main app component. Update app.component.html:

<app-charts></app-charts>

Step 8. Running the Application

Run your Angular application to see the charts in action:

ng serve --open

Open your browser and navigate to http://localhost:4200. You should see the different types of charts displayed with the sample data.

HeatMap

Bar Chart

Round

Line chart

Comparison

Conclusion

By following these steps, you can integrate Chart.js into your Angular application and create various types of charts to visualize your data. Chart.js provides a powerful and flexible way to enhance your web applications with interactive and visually appealing charts.


Similar Articles