VipPunkJoshers Droopy VipPunkJoshers Droopy - 5 months ago 29
HTML Question

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?

Answer Source

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, {....});

  }

}