How to implement chart.js in angular 2?

Member

by deron , in category: Javascript , a year ago

How to implement chart.js in angular 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a year ago

@deron 

To implement Chart.js in Angular 2, you can follow the steps given below:

  1. Install Chart.js package using npm: npm install chart.js --save
  2. Install typings for Chart.js: npm install --save @types/chart.js
  3. Import the necessary modules in your Angular application: Open the app.module.ts file and add the following imports: import { ChartsModule } from 'ng2-charts'; import 'chart.js';
  4. Add ChartsModule to the imports array in @NgModule decorator: imports: [ // other imports ChartsModule ],
  5. Create a component to display the chart: ng generate component chart
  6. In the component's HTML template, add the chart element:
  7. In the component's TypeScript file (chart.component.ts), define the chart data and options: import { Component } from '@angular/core'; @Component({ selector: 'app-chart', templateUrl: './chart.component.html', styleUrls: ['./chart.component.css'] }) export class ChartComponent { public lineChart = { type: 'line', legend: true, labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], data: [ { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' }, { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' } ], options: { responsive: true } }; }
  8. Finally, add the component to the main application template (app.component.html):
  9. Run the application: ng serve


Now, you should be able to see the chart rendered in your Angular 2 application. Make sure to adjust the chart data and options according to your requirements.

Related Threads:

How to implement caching using etag in angular?
How to use chart.js in angular?
How to zoom charts in chart.js using angular?
How to update data chart in async way in angular chart.js??
How to implement logging in Yii?
How to use chart.js in angular.js?