NG2-Charts + Ionic4

Hi all,

has anyone been able to use Ng2-Charts with Ionic 4? I followed the Ionic3 tutorial linked below but I am running into the error “Can’t bind to ‘datasets’ since it isn’t a known property of ‘canvas’”

https://www.djamware.com/post/598953f880aca768e4d2b12b/creating-beautiful-charts-easily-using-ionic-3-and-angular-4

I also followed steps in this community and at their issue tracker (https://github.com/valor-software/ng2-charts/issues/553)

Is there an alternate charting package that has been tested on Ionic 4 RC0?

Thanks!

hello,
show html and related ts code. Seems that you use something wrong in a canvas tag.

Best regards, anna-liebt

Hi thanks for the reply.

I created a new blank app (ionic start ng2chart blank --type=angular) and followed this tutorial: https://valor-software.com/ng2-charts/

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { ChartsModule } from 'ng2-charts';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, ChartsModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

home.page.html:

<ion-content padding>
  <div class="row">
    <div class="col-md-6">
      <div style="display: block;">
      <canvas baseChart width="300" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)">
	   </canvas>
      </div>
    </div>
  </div>
</ion-content>

home.page.ts

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
	
	public lineChartData:Array<any> = [
	  {data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
	  {data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
	  {data: [18, 48, 77, 9, 100, 27, 40], label: 'Series C'}
	];
	public lineChartLabels:Array<any> = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
	public lineChartOptions:any = {
	  responsive: true
	};
	public lineChartColors:Array<any> = [
	  { // grey
		backgroundColor: 'rgba(148,159,177,0.2)',
		borderColor: 'rgba(148,159,177,1)',
		pointBackgroundColor: 'rgba(148,159,177,1)',
		pointBorderColor: '#fff',
		pointHoverBackgroundColor: '#fff',
		pointHoverBorderColor: 'rgba(148,159,177,0.8)'
	  },
	  { // dark grey
		backgroundColor: 'rgba(77,83,96,0.2)',
		borderColor: 'rgba(77,83,96,1)',
		pointBackgroundColor: 'rgba(77,83,96,1)',
		pointBorderColor: '#fff',
		pointHoverBackgroundColor: '#fff',
		pointHoverBorderColor: 'rgba(77,83,96,1)'
	  },
	  { // grey
		backgroundColor: 'rgba(148,159,177,0.2)',
		borderColor: 'rgba(148,159,177,1)',
		pointBackgroundColor: 'rgba(148,159,177,1)',
		pointBorderColor: '#fff',
		pointHoverBackgroundColor: '#fff',
		pointHoverBorderColor: 'rgba(148,159,177,0.8)'
	  }
	];
	public lineChartLegend:boolean = true;
	public lineChartType:string = 'line';
}

Here are the errors I receive:

Please note I have tried many different suggestions such as:

  1. Using this as my import: import { ChartsModule } from ‘ng2-charts/ng2-charts’;
  2. Importing the above into my home.page.ts as well
  3. Most suggestions listed here: https://github.com/valor-software/ng2-charts/issues/553
  4. Many other permutations as well.

Thanks for any help anyone can provide

Hello,

is chartjs installed?

Best regards, anna-liebt

Don’t know what’s the solution, but just a hint, the problem is most probably, I would say, not related to Ionic v4 but rather to Angular v7 (I guess you are using the Angular version) no?

ng2-charts is build with Angular v2 so that’s maybe the root of the incompatibility?

if that’s correct, have you had a look on the net if you found something about this incompatibility?

As per the tutorial, I ran these commands to install the requirements

npm install ng2-charts --save
npm install chart.js --save

Yes I believe the incompability is to do with the latest Angular version. Is there another charting library known to work with Ionic 4 + Angular 7?

Thanks

Hello,
chartjs works with ionic 4.

The error message indicates that is something wrong with the import of ChartsModule and can’ t used in html. Does your ide have the abillity to check, that the import statement is correct? If you use visual code, then there are extensions that will checks this for you.

If you wanna go further with chartjs, then install additionally related types. Put canvas into a container (imho best is a div), add import statement for chartjs to your ts, fetch canvas and container each with viewchild and follow chartjs tutorial.

BVest regards, anna-liebt

I don’t know if there are others, I tend to not look for Angular compatible lib anymore but rather to Web Components. But as @anna_liebt said, that might not be the problem, it was just a suggestion on my side

That being said, if you want to go experimental and don’t have that many requirements, for my pet project DeckDeckGo, I have published a Web Component to plot some charts easily using d3js. It’s open source, if you want to use it, go for it: https://github.com/deckgo/deckdeckgo-charts

But like I said, it’s a simple component, I don’t plan to add much more features, it’s only for plotting graph, but if that suit your needs have fun

I use ngx-charts with Angular 7

ngx-charts looks promising. Is there a guide or a reference you can recommend on how to get it working with Ionic 4?

Helo,
you have chartjs installed. You can use it directly
Check in package.json, that you have installed chartjs. You see something like that

"chart.js": "^2.7.3",

If not, install chartjs.
Next to make codeing more comfortable install typings from https://www.npmjs.com/package/@types/chart.js, then you have intellisense. Makes live easier.

npm install --save @types/chart.js

Now you should have in package.json something like

"@types/chart.js": "^2.7.42",

Next step is to use it. Add to your html. The chartcontainer is need for responsibility, otherwise it is not necessary. On chartcanvas is the chart rendered. That is all you need in html. Style with classes on div, canvas whatever you want.

<div #chartContainer class='chart-container'>
        <canvas  #chartcanvas id="myChart"></canvas>
    </div>

Next is import the lib. in your ts.
import { Chart } from 'chart.js';

To fetch a standard html tag like div, canvas, you also need to import childview and ElementRef. More Imports not needed…

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

Create a variable in your class that will hold your chart. It will be fill later.

myChart: Chart;

Next is to fetch your html tags into a variable with viewchild. You do this inside your class.

@ViewChild('chartContainer') chartcontainer: ElementRef;
  @ViewChild('chartcanvas') chartcanvas: ElementRef;

viewchild references are ready in ngAfterViewInit lifecyle

ngAfterViewInit() {

    this.createChart();

  }

Create and fill your chart with datas like example.

createChart() {   
    this.myChart = new Chart(this.chartcanvas.nativeElement, {
      type: 'horizontalBar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
          ],
          borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        maintainAspectRatio: false,
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  }

You are done. If you wanna change datas etc. you can do this like

this.myChart.data = this.yourdata;
    this.myChart.config.options = youroptions;
    this.myChart.update();

If you need that the dimensions of your chart change, then you change the dimension of chartcontainer before you set the new datas and chart dimensions follow, like

this.chartcontainer.nativeElement.style.height = this.yourheight + 'px';

Best regards, anna-liebt.

3 Likes

Thanks for that - it’s working now! I had to tweak your code a bit to get it going:

  1. Including the option “maintainAspectRatio” caused the chart to not render and there were no errors produced. Removing this property allowed it to render.

  2. adding the myChart variable to the class

Thanks again for your help, much appreciated

1 Like

Hello,
sorry for 2. I forgot one line and have add it.
to 1. Hmm, should work, maybe div needs a width or height. I set this with css to initial values, but now it is working in your project, so I do not investigate any further time.

Best regards, anna-liebt

1 Like

I’ve only used it in Angular using their own docs.

1 Like

I’ve had good experience using chartjs which integrate nicely with ionic.

I know the solution for this and you need to import the chartsmodule on follwing
pages
1)app module
2)home.ts
3)home.module

It will work!!

Admittedly a newbie, but I followed these instructions and gone over to make sure it’s accurate, and checked the json to see that everything is installed, but even without filling in the chart I get an error “ERROR TypeError: this.createChart is not a function
at HomePage.push…/src/app/home/home.page.ts.HomePage.ngAfterViewInit”

Any thoughts what I’m missing?

Hello! I am facing the same issue. How did you solve it ? Till now, I can’t solve it . Thank you very much .

I rollback to older version 2.2.3. this error will be gone. but facing another error like Error: Template parse errors: Can’t bind to ‘datasets’ since it isn’t a known property of ‘canvas’. (" <canvas #chartcanvas id=“myChart” .