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.