How to use chart.js in angular?

by cortez.connelly , in category: Javascript , 5 months ago

How to use chart.js in angular?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 5 months ago

@cortez.connelly 

To use chart.js in an Angular application, you can follow these steps:

  1. Install chart.js and ng2-charts: First, install the chart.js library and the ng2-charts wrapper library in your Angular project using npm. Run the following command in the terminal:
1
npm install chart.js ng2-charts


  1. Import the necessary modules: In your Angular module file (e.g., app.module.ts), import the ChartModule from ng2-charts and ChartsModule from chart.js. Add them to the imports array in the @NgModule decorator.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ChartModule } from 'ng2-charts';
import { ChartsModule } from 'chart.js';

@NgModule({
  declarations: [
    // your components
  ],
  imports: [
    BrowserModule,
    ChartModule,
    ChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


  1. Use the ng2-charts directive in your component template: In your component template file, you can use the ng2-charts directive to create a chart. For example, you can create a line chart by adding the following code:
1
<canvas baseChart [datasets]="lineChartData" [labels]="lineChartLabels" [options]="lineChartOptions" [colors]="lineChartColors" [legend]="lineChartLegend" [chartType]="lineChartType"></canvas>


  1. Define the chart data and options in your component: In your component TypeScript file, define the chart data and options that you want to display in the chart. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { Component } from '@angular/core';

@Component({
  selector: 'app-my-chart',
  templateUrl: './my-chart.component.html',
  styleUrls: ['./my-chart.component.css']
})
export class MyChartComponent {
  public lineChartData = [
    { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' }
  ];
  public lineChartLabels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
  public lineChartOptions = {
    responsive: true
  };
  public lineChartColors = [];
  public lineChartLegend = true;
  public lineChartType = 'line';
}


  1. Update the chart data dynamically: You can update the chart data dynamically by modifying the values of the chart data arrays in your component. Chart.js will automatically update the chart in the template.


These are the basic steps to use chart.js in an Angular application. You can refer to the official documentation of chart.js and ng2-charts for more customization options and advanced features.