Guide: How to add ng2-charts into Ionic

Hi All,

I had some problems in adding ng2-charts into my ionic project and after reading a lots of posts I finally managed to get it work so this is how it work for me:

Step 1: Install ng2-charts and chart.js into your project

  • In you project folder run the following command:
    npm install --prefix . ng2-charts --save
    This command will create ng2-charts folder in your node_module folder.

  • Go to src/assets folder and run the following command:
    npm install --prefix . chart.js --save (With the help of radek79’s comment)
    This command will create chart.js folder in your src/assets/node_module folder.

Step 2: Import ChartsModule

Go to app.module.ts:

  • Import the ChartsModule:
    import {ChartsModule} from 'ng2-charts/components/charts/charts';

  • Add to imports section below:
    imports: [
    ChartsModule
    ]

Step 3: Include Javascript files into your html file in app.component.ts

You need to add two files, the first one is Chart.bundle.js and the second one is Chart.js, I added them in the code because I need the chart functionality for specific users:

let body = document.getElementsByTagName('body')[0];
let bundlejs = document.createElement('script');
bundlejs.setAttribute('src','assets/node_modules/chart.js/dist/Chart.bundle.js');
body.appendChild(bundlejs);
let chartjs = document.createElement('script');
chartjs.setAttribute('src','assets/node_modules/chart.js/dist/Chart.js');
body.appendChild(chartjs);

I added them into the body but you can add them to the head (you can also use min.js files instead).

That’s it

You can copy-paste the example code located in http://valor-software.com/ng2-charts/ to see the result.

Example from valor-software:
In the .html file add canvas DOM element:

<canvas baseChart
        [datasets]="barChartData"
        [labels]="barChartLabels"
        [options]="barChartOptions"
        [legend]="barChartLegend"
        [chartType]="barChartType"
        (chartHover)="chartHovered($event)"
        (chartClick)="chartClicked($event)"></canvas>

In the .ts file add:

public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels:string[] = [‘2006’, ‘2007’, ‘2008’, ‘2009’, ‘2010’, ‘2011’, ‘2012’];
public barChartType:string = ‘bar’;
public barChartLegend:boolean = true;

public barChartData:any[] = [
{data: [65, 59, 80, 81, 56, 55, 40], label: ‘Series A’},
{data: [28, 48, 40, 19, 86, 27, 90], label: ‘Series B’}
];

// events
public chartClicked(e:any):void {
console.log(e);
}

public chartHovered(e:any):void {
console.log(e);
}


I hope that it will be helpful for you.

4 Likes

npper, Thank you for posting this guide. I feel like I’m almost there except I’m not sure if I still need to import CHART_DIRECTIVES in my component that displays a chart using ng2-charts. Could you please post an example of you rendered a sample chart please?
I’m specifically running into issues when following http://plnkr.co/edit/7fGsiuRjcF0M0Ffeoml2?p=preview

in my about.html

<div style="display: block">
	<base-chart
      class="chart"
      [datasets]="datasets"
      [labels]="labels"
      [options]="options"
      [chartType]="'line'">
    </base-chart>

in about.ts

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

import { NavController } from ‘ionic-angular’;

@Component({
selector: ‘page-about’,
templateUrl: ‘about.html’

})
export class AboutPage {

public datasets = [{
	label: "# of Votes",
	data: [12, 19, 3, 5, 2, 3]
}];
public labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];
public options = {
scales: {
  yAxes: [{
    ticks: {
      beginAtZero: true
    }
  }]
}

};

constructor(public navCtrl: NavController) {
}

ngOnInit() { 

}

my output from ‘ionic build’

[18:47:37]  Error: Template parse errors:
[18:47:37]  Can't bind to 'datasets' since it isn't a known property of 'base-chart'.
[18:47:37]  1. If 'base-chart' is an Angular component and it has 'datasets' input, then verify that
            it is part of this module.
[18:47:37]  2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema'
            of this component to suppress this message.
[18:47:37]  ("
[18:47:37]  <base-chart
[18:47:37]  class="chart"
[18:47:37]  [ERROR ->][datasets]="datasets"

After looking at it again, it looks like I was using an outdated way of using ng2-charts. The code in about.html should have been:

<canvas baseChart width="400" height="400"
      [datasets]="datasets"
      [labels]="labels"
      [options]="options"
      [chartType]="'line'">
    </canvas>

Also, just fyi, when running npm install chart.js --save inside of src/assets. I had to cd into src/assets run ‘npm install --prefix . chart.js --save’ (notice the ‘.’) in order to avoid chart.js being installed into my main directory vs src/assets. Not sure if anyone else will have this problem, but thought I’d mention it.

1 Like

Great, I see that you got it to work, I fixed the npm command as wrote and copied an example from http://valor-software.com/ng2-charts/ site. Thank you.

Thanks nnper for your steps … My doubt … you have done it for ionic2 you said that’s cool in fact i am trying with that but got stuck with one part … In your step 3 mentioned import js file to html file (in my case about.html tab ) it will not allow any js file import how do i do and where do i import js file …Very sorry i am very much new to this technology and i need your kind help Thanks in advance

One more question will it works with ionic framework RC2 , Running on device also getting blank screen

Hi brkulkarni89,

Do you see any errors in the browser’s inspect view?

There are 2 ways to import the javascript files:

You can add them to the index.html file located in the src folder as follow:
<script src=“assets/node_modules/chart.js/dist/Chart.bundle.js”></script>
<script src=“assets/node_modules/chart.js/dist/Chart.js”></script>

or you can add the files in the code as I wrote, this part is a little bit tricky because you need to add these imports in the parent page before you actually use it. try to add the two imports above to the page and see if it works for you.

Open the inspect view in your browser and check if the imports added to the page.

I needed to upgrade the beta version for it to work, it work on RC2.

1 Like

Thanks a lot nnper for your kind support and beautiful reply … Yes its working absolutely fine with RC2 .

Some more questions are there i think (100%) a right person to ask questions

Q1) . What is the difference between RC2 and RC0 ?
Q2). If we use Javascript libraries or else cordova plugins in our app will effect the performance rather than using native plugins or components ?

Please don’t mind after seeing my questions since i am very much new to this technical field and special with mobility …

Thanks

Hi brkulkarni89, see https://github.com/driftyco/ionic/blob/master/CHANGELOG.md, there are some upgrades and bug fix.
That the performance impact of the cordova plugin is in the boot time, I don’t think that you will notice any performance issue while running the app.

This works great thank you. When I update lineChartData, I’m not seeing the chart update. I do see the correct values on mouseover, but do I need to “re-render” the chart??

@nnper , I tried the above but am having difficulty importing the js files :confused:

I get a 404 on loading the scrips as described below:

Uncaught Error: Cannot find module "ng2-charts/components/charts/charts"
    at Object.<anonymous> (main.js:115023)
    at __webpack_require__ (bootstrap 8b96fb5…:19)
    at Object.<anonymous> (main.js:140085)
    at __webpack_require__ (bootstrap 8b96fb5…:19)
    at bootstrap 8b96fb5…:65
    at bootstrap 8b96fb5…:65
Chart.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
Chart.js Failed to load resource: the server responded with a status of 404 (Not Found) 

Im on RC5. (though I don’t see any changes regarding assets from RC5 to 2.0.1)

EDIT1: I resolved the 404 through importing the scripts from cloudflare’s CDN:

  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>

The first error is still there though:

Uncaught Error: Cannot find module "ng2-charts/components/charts/charts"
    at Object.<anonymous> (main.js:115023)
    at __webpack_require__ (bootstrap 8b96fb5…:19)
    at Object.<anonymous> (main.js:140085)
    at __webpack_require__ (bootstrap 8b96fb5…:19)
    at bootstrap 8b96fb5…:65
    at bootstrap 8b96fb5…:65

EDIT2: I resolved the second error, by looking at ng2-charts github repo. The import has changed to:
import { ChartsModule } from 'ng2-charts/ng2-charts';

Hi @jjrchrds,

Sorry for the late response, Look at http://valor-software.com/ng2-charts in the line chart section, the click button is changing the chart values, you should probably need to update to the ng2-chart version.

They changed the package so after updating the ng2-chart version you need to change the ChartsModule import as written by @apaliku or use this import:
import {ChartsModule} from ‘ng2-charts/charts/charts’;

@jjrchrds To update the values you need to re-build the whole data/dataset array + objects.

This is due to angular2 binding. If you take a look at http://valor-software.com/ng2-charts , you’ll see the following comment when they rebuild the dataset:

    let clone = JSON.parse(JSON.stringify(this.barChartData));
    clone[0].data = data;
    this.barChartData = clone;
    /**
     * (My guess), for Angular to recognize the change in the dataset
     * it has to change the dataset variable directly,
     * so one way around it, is to clone the data, change it and then
     * assign it;
     */
1 Like

Just came along to say: “Thank you nnper!

I was getting all kinds of errors, until I solved the problem following your procedure, I’m not sure what I did wrong, but now it is working.
While searching on the internet, I’ve found so many people struggling to have a chart in their apps, it is ridiculous that people have to waste so much time to get a basic functionality like a chart!

1 Like

I just logged in to say, like Gono said: Thanks, thanks, thanks nnper!!!

2 Likes

Thanks nnper!!!, This tutorial has saved me a lot of time.