Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How implement Chart.js in Angular 2?

I am using the latest version of Angular 2, V4.0.0 and I want to use graphs from the Chart.js library in my project without many complications.

How can I implement Chart.js in my angular project that does not give me problems in the final production?

like image 779
jojemapa Avatar asked Apr 01 '17 01:04

jojemapa


2 Answers

You can implement Chart.js in a simple way with the following instructions:

1. Create a new project with angular-cli, skip if you already have one created

ng new example-chartjs

2. Install Chart.js in your project

npm install chart.js --save

3. Import Chart into its component

import Chart from 'chart.js';

4. Use Chart in your view and component

In your view:

<canvas id="myChart" width="400" height="400"></canvas>

In your component:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

The component should look similar to the following

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

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}

Another alternative to use is to include the library from the file ".angular-cli.json"

1. Include in the scripts the library

"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]

2. Declare a variable of type "any" in the controller

declare var Chart:any;

3. Use Chart in your view and component

In your view:

<canvas id="myChart" width="400" height="400"></canvas>

In your component:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

The component should look similar to the following

import { Component, OnInit } from '@angular/core';

declare var Chart:any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}
like image 160
jojemapa Avatar answered Sep 21 '22 17:09

jojemapa


First
npm install chart.js --save

Second
npm install @types/chart.js --save

Third - import Chart into component this way
import * as Chart from 'chart.js';

like image 24
aleQ Avatar answered Sep 20 '22 17:09

aleQ