How to use chart.js in angular.js?

Member

by deron , in category: Javascript , 2 months ago

How to use chart.js in angular.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 2 months ago

@deron 

To use chart.js in Angular.js, follow these steps:

  1. Install Chart.js: Run the following command in your project folder to install Chart.js using npm:
1
npm install chart.js --save


  1. Import Chart.js: In your Angular.js component file (e.g., app.component.ts), import the Chart.js library:
1
import { Chart } from 'chart.js';


  1. Create a Canvas element: In the HTML template file (e.g., app.component.html), add a canvas element with a unique identifier, where you want to display the chart:
1
<canvas id="myChart"></canvas>


  1. Initialize Chart.js in your component: In your Angular.js component file, create a reference to the canvas element and get its 2D context, then create the chart using the Chart.js library:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { Component, AfterViewInit } from '@angular/core';

export class AppComponent implements AfterViewInit {
  ngAfterViewInit() {
    const canvas = <HTMLCanvasElement>document.getElementById('myChart');
    const ctx = canvas.getContext('2d');

    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Label 1', 'Label 2', 'Label 3'],
        datasets: [{
          label: 'Data',
          data: [10, 20, 30],
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          borderColor: 'rgba(75, 192, 192, 1)',
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  }
}


  1. Customize your chart: You can modify the chart options and data according to your requirements. Refer to the Chart.js documentation for more customization options.
  2. Save and run your Angular.js application: Save the changes, and run your Angular.js application. You should now see the chart displayed on the specified canvas element.


Note: Make sure to import Chart.js and use the correct library version based on your Angular.js version.