Chart.js v2 not rendering in Angular 2

Created on 18 Mar 2016  ·  6Comments  ·  Source: chartjs/Chart.js

I was able to render charts with v1.0.2 in Angular 2, but with v2.0.0 it doesn't render anything in the screen and doesn't log anything on the console.

I'm using the example provided in v2 docs:

constructor(el: ElementRef) {}

ngAfterViewInit() {
    var ctx = this.el.nativeElement.firstChild.getContext("2d");
    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
                        }
                    }]
            }
        }
      });
  }
support

Most helpful comment

@hertz1 this issue seems to be that the <chart> component has no size. V2 generally sizes to fit the parent. I added a container div around the canvas that is 100% width and height. Updated the part that gets the canvas context.

The result is: https://plnkr.co/edit/RbhYj4uEeSC8MSZZHBe3?p=preview

All 6 comments

@hertz1 do you get any errors in the console?

@etimberg No, nothing. I've added a console.log(ctx) before the chart instantiation, it logs the canvas context:

CanvasRenderingContext2D {
  canvas: <canvas>,
  globalAlpha: 1,
  globalCompositeOperation: "source-over",
  strokeStyle: "#000000",
  fillStyle: "#000000",
  shadowOffsetX: 0,
  shadowOffsetY: 0,
  shadowBlur: 0,
  shadowColor: "rgba(0, 0, 0, 0)",
  mozCurrentTransform: Array[6]
}

Is it possible to create a jsfiddle demoing the issue? I definitely know that it works inside angular.

@etimberg I've created a plunker demoing the issue. Link: https://plnkr.co/edit/xh5FRigqZ9xCvbNoBo2m

@hertz1 works for me, take a look here:

https://github.com/evoila/angular2-chartjs2

@hertz1 this issue seems to be that the <chart> component has no size. V2 generally sizes to fit the parent. I added a container div around the canvas that is 100% width and height. Updated the part that gets the canvas context.

The result is: https://plnkr.co/edit/RbhYj4uEeSC8MSZZHBe3?p=preview

Was this page helpful?
0 / 5 - 0 ratings