我正在使用VisualStudio。
我尝试使用ViewChild,但后来我决定尝试官方方式:
https://www.chartjs.org/docs/latest/getting-started/usage.html
"@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>
"
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
}
}]
}
}
})
}
画布最初使用指定的维度进行渲染,但当
当画布设置为
宽度
和
高度
=“0”,它将变为空。
<canvas _ngcontent-c2="" height="400" id="myChart" width="400"></canvas>
生成的HTML元素:
<canvas _ngcontent-c2="" height="0" id="myChart" width="0" class="chartjs-render-monitor" style="display: block; height: 0px; width: 0px;"></canvas>
我可以改变高度,但是
画布完全是空的
我还尝试使用ViewChild解决方案,但当我将有效的内容传递给Chart()时,我得到了相同的结果:宽度和高度设置为“0”,画布为空。
//var ctx = (<HTMLCanvasElement>this.chartCanvas.nativeElement).getContext("2d")
var ctx = document.getElementById("chartCanvas") as HTMLCanvasElement
chart = []
// and this in the HTML template
<canvas ...>{{ chart }}</canvas>
使用这种方法,当我没有错误时,图表结果为[Object]。
有人知道为什么不创建图表吗?