[Chartjs]-Angular 5 chart.js Failed to create chart

2👍

As the documentation said:

To create a chart, we need to instantiate the Chart class. To do this,
we need to pass in the node, jQuery instance, or 2d context of the
canvas of where we want to draw the chart

So your code should look like this:

var canvas = <HTMLCanvasElement> document.getElementById("canvas");
var ctx = canvas.getContext("2d");
this.chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ["a", "b", "c", "d", "e"],
        datasets: [
          {
            title: "Some Data",
            values: [25, 40, 30, 35, 100],
            borderColor: "#3cba9f",
            fill: false
          },
        ]
      },
      options: {
        legend: {
          display: false
        },
        scales: {
          xAxes: [{
            display: true
          }],
          yAxes: [{
            display: true
          }],
        }
      }
    });
}

4👍

in component.html

The problem is the *ngIf. The canvas doens’t exist as long as *ngIf == false and can thus not be found by chart.js. Change the tag into and it should work

<div [hidden]="!chart">
  <canvas id="canvas">{{ chart }}</canvas>
</div>

Leave a comment