Chart.js 2.0 - How to?

I found out that, from the doc, there is no label for that type of chart! This is sad :frowning:

Hey, @icarus_31 thanks for you reply, can you more specific?
because I have this error:
EXCEPTION: ReferenceError: Chart is not defined
by following the guide from http://valor-software.com/ng2-charts/

and if i add the this in the one of a page.ts
import ‘chart.js/dist/Chart.min’

and I get this error:
TypeError: (intermediate value)[this.chartType] is not a function

Im so confusion now.
and the version of chart.js is “chart.js”: “2.1.3”,
and the version of ng2-charts is “ng2-charts”: “^1.0.3”.

And you share the step how you get your problem fix?
Thank you so much and have a great day

Finally, I found the issues.

  1. chart.js have to be 1.0.2. other version wont works.
  2. we can not import the chart.js/chart.min in the ts file. This will end up with the chart not defined.

So we have to put the chart.js to the libs file and add in the www/index.html.
and we have to modifier little bit the gulp file if you want to loading the js locally.

TODO: I hope the ng2-charts will fix those version issues.

FWIW, here is a datapoint. It’s not Ionic, but I do have an Angular2 application (using RC1) that uses chart.js version 2.1.2. I have the following line in a TypeScript file:

var Chart = require<any>('chart.js/src/chart');

I use @ViewChild to grab the canvas element, and pass its nativeElement member as the first argument to the Chart constructor. It works.

1 Like

Hi @rapropos,

Would you mind to show us the complete code related to the chart? Not sure to understand the @ViewChild

Thanks

Keep in mind that (a) I’m not using ng2-charts, and (b) this is a stock Angular2 app, not Ionic.

var Chart = require<any>('chart.js/src/chart');

@Injectable()
@Component({
  selector: 'donut-chart',
  template: `<canvas #canvas [height]="height" [width]="width"></canvas>`
})
export class DonutChart implements AfterViewInit {
  @ViewChild('canvas') private _canvas:ElementRef;
  @Input() height:number;
  @Input() width:number;
  @Input() values:number[];
  @Input() labels:string[];
  @Input() colors:string[];
  @Input() title:string;

  ngAfterViewInit():void {
    let data:any = {
      labels: this.labels,
      datasets: [{
        data: this.values,
        backgroundColor: this.colors,
      }]
    };
    let options:any = {
      // this avoids 0x0 charts
      responsive: false,
    };
    if (this.title) {
      options.title = {
        display: true,
        text: this.title,
      }
    }
    let chart = new Chart(this._canvas.nativeElement, {
      type: 'doughnut',
      data: data,
      options: options,
    });
  }
}

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.