Chart.js 2.0 - How to?

Thanks for the code.

By the way, do you confirm that no labels is available for doughnut chart?

Labels work fine for me using this component, in that they display in a legend above the donut, as they look in the screencaps in the docs.

oh! 2.0 is now official! Great

Thanks

For people who are interested by using Chart.js 2.x.x and waiting for ng2-chart to handle that new version

index.html

<script src="Chart.js"></script>

and putting the Chart.js file in your www directory

Ionic HTML page file

Typescript file

declare var Chart;

and taking the Chart.js example

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

You should see the chart in your page!

2 Likes

I still think @ViewChild is a better choice than fooling with the DOM this way.

you are probably right. I am just not good as you. :slight_smile:

I want to see my graph first and then see what I can do with your code sample.

Hi @rapropos. Me again :wink:

I just created a new component and tried to use it inside my Ionic html page. It looks good, buuuut when my directive is called, the data is not there yet!

Any idea how I could wait for the data before showing the graph?

Basically, I have practically all the code you suggested and in my html page I have:

<doughnut-chart [width]="400" 
                [height]="400"
                [values]="_chartData"
                [labels]="_chartLabels"
                [colors]="_chartColors">
</doughnut-chart>

The issue is with [values]. When the directive is called, the _chartData is not loaded yet. It seems to go well until the “new Chart” is called. After that, I have that first error inside Chrome:

TypeError: Cannot read property 'custom' of undefined
    at .<anonymous> (http://localhost:8100/Chart.js:2588:22)
    at Array.map (native)
    at Chart.defaults.doughnut.legend.labels.generateLabels (http://localhost:8100/Chart.js:2584:26)
    at Chart.Legend.Chart.Element.extend.buildLabels (http://localhost:8100/Chart.js:6086:58)
    at Chart.Legend.Chart.Element.extend.update (http://localhost:8100/Chart.js:6036:9)
....

If you have any idea, don’t hesitate to share with me. Thanks!

It doesn’t look like the problem is with values, but with labels (at least according to that error message). There are a number of ways to deal with problems like this, including aggressive construction (always making sure even a dummy instance is available), the Elvis operator (?: that short-circuits operation if its operand is null), or the AsyncPipe that waits for some asychronous operation.

Hey @icarus_31. It seems that some parts of your reply are missing:

index.html

** and putting the Chart.js file in your www directory

Ionic HTML page file

Typescript file

declare var Chart;

Could you please elaborate on the missing parts? And are you using only Chart.js 2.x?
Thanks in advance!

Hi, @icarus_31,

I don’t understand your explanation, could explain to me, how I have to do to import chart.js in my project ?

Thank you.

I did it by

import ‘…/node_modules/chart.js/dist/Chart.bundle.min.js’;

in app.ts. But im not quite sure if this is the way to go

1 Like

In my example (that I corrected ), I put the chart.js file at the same place as the index.HTML and add a <script … > to add it.

I am sure there is a better way and you will probably found one in the forum

Ok thank you. Do you have test chart.js on iOS ? Because, I have a bar graph on android but on iOS I just have a little black graph …

Did you try to use the Safari debugger? It works pretty neat at my iOs device.

Yes, I’m using the Safari debugger, and I don’t have errors.

Ok I fixed the problem, I have to add responsive: false on iOS …

Nice :slight_smile: I also got it to work and it plays quite nicely with ionic. A few pitfalls, but the docs and examples are very complete.

Yes it’s really nice !

Nice, however a couple of questions when used in Ionic2

What’s the purpose of:

selector: ‘donut-chart’

and how can it be integrated in a different page/component view, I meant, let’s say that you have your rootPage, then a list page and then in the detail-page you want to add a ion-card with the chart.

In my test what happening is that I can see the chart (donut) but the page lost its navBar, back button and the look and feel of the rest of the standard Ionic page.

for instance, I’ve this code in my html of the page:

<ion-header>
  <ion-navbar>
    <button menuToggle>
        <ion-icon name="trackerDetail"></ion-icon>
    </button>
    <ion-title>Your progress</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="tracker">
    <div>
        <canvas #canvas width="300" height="200"></canvas>
        <ion-card>
            <ion-card-content>
                <h1>This is your tracked progress</h1>
            </ion-card-content>
        </ion-card>
    </div>
</ion-content>

and my tracker-detail.ts file as follow:

import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {DbService} from '../../services/db-service';
import {ViewChild, ElementRef, AfterViewInit} from '@angular/core';

declare var Chart: any;

@Component({
  selector: 'donut-chart',
  templateUrl: 'build/pages/tracker-details/tracker-details.html'
})
export class TrackerExamDetailPage {
  @ViewChild('canvas') private canvas:ElementRef;

  constructor(public nav: NavController, public navParams: NavParams, public dbService: DbService) {
    this.nav = nav;
    let progressExam = navParams.get('progressExam');
  }

  ngAfterViewInit() {
    let ctx = this.canvas.nativeElement;
    let myChart = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ['yolo', 'dolo', 'solo'],
        datasets: [{
          data: [300, 50, 100],
            backgroundColor: [
                "#FF6384",
                "#36A2EB",
                "#FFCE56"
            ],
            hoverBackgroundColor: [
                "#FF6384",
                "#36A2EB",
                "#FFCE56"
            ]
        }]
      }
    });
  }
}

The result is kind of annoying:

as you can see the side-menu is partially transitioned and chart seems to be overlapping the incoming HTML page and navBar disappeared. Assuming a standard blank ionic2 template with side-menu and 3 pages like (rootPage, list page, detail page).

The point of selector: 'donut-chart' is that the component is designed to be used like this:

<ion-content>
<ion-card>
<ion-card-content>
<h1>header</h1>
<donut-chart width="200" height="300" other-parameters></donut-chart>
</ion-card-content>
</ion-card>
</ion-content>

It’s not supposed to be smashed into the code of a page component.