I'm stuck trying to use Chart.js in Angular4. I'm using Visual Studio.
I tried to use ViewChild but then I decided to try the official way:
https://www.chartjs.org/docs/latest/getting-started/usage.html
package.json:
"@angular/core": "4.2.5",
"@types/chart.js": "^2.7.40",
"chart.js": "^2.7.3",
my-chart.html:
<canvas id="myChart" width="400" height="400"></canvas>
or
<canvas #chartCanvas [style.width]="width" [style.height]="height"></canvas>
"my-chart.ts:
import { Chart } from "chart.js"
export class SalesChart implements OnInit {
@Input("chartWidth") width: string = "10%"
@Input("chartHeight") height: string = "20%"
@ViewChild("chartCanvas") private chartCanvas:any
// when click the button:
drawChart() {
// new Chart does not accep HTMLElement
// var ctx = document.getElementById("myChart")
var myChart = new Chart("myChart", {
type: 'bar',
data: {
labels: ["Red", "Blue"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
The canvas is initially rendered with the assigned dimensions but when the drawChart() is executed the canvas is set with width and height = "0" and it become empty.
Initial HTML element:
<canvas _ngcontent-c2="" height="400" id="myChart" width="400"></canvas>
Resulting HTML element:
<canvas _ngcontent-c2="" height="0" id="myChart" width="0" class="chartjs-render-monitor" style="display: block; height: 0px; width: 0px;"></canvas>
I can change the with/height but the canvas is absolutely empty.
I also tried using the ViewChild solution but when I pass something valid to Chart() I have the same result: width and height set to "0" and empty canvas.
//var ctx = (<HTMLCanvasElement>this.chartCanvas.nativeElement).getContext("2d")
var ctx = document.getElementById("chartCanvas") as HTMLCanvasElement
I found some tutorials that use:
chart = []
// and this in the HTML template
<canvas ...>{{ chart }}</canvas>
With this approach when I have no errors the chart result to be [Object Object].
Someone have any idea why the chart is not created?