angular - 如何在 Angular4 中使用 Chart.js?
问题描述
我一直在尝试在 Angular4 中使用 Chart.js。我正在使用 Visual Studio。
我尝试使用 ViewChild 但后来我决定尝试官方方式:
https ://www.chartjs.org/docs/latest/getting-started/usage.html
包.json:
"@angular/core": "4.2.5",
"@types/chart.js": "^2.7.40",
"chart.js": "^2.7.3",
我的chart.html:
<canvas id="myChart" width="400" height="400"></canvas>
or
<canvas #chartCanvas [style.width]="width" [style.height]="height"></canvas>
“我的图表.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
}
}]
}
}
})
}
画布最初以指定的尺寸呈现,但当执行drawChart()时,画布设置为宽度和高度=“0”,它变为空。
初始 HTML 元素:
<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>
我可以更改 with/height 但画布绝对是空的。
我也尝试使用 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 Object]。
有人知道为什么没有创建图表吗?
解决方案
我通常通过primeng使用chart.js,即使我不想使用primeng,我也会效仿他们,因为我觉得它很干净。你可以在这里看到他们是如何实现它的:https ://github.com/primefaces/primeng/blob/master/src/app/components/chart/chart.ts
推荐阅读
- java - 为什么它不能从文本文件中读取用户输入的名称和显示信息
- powershell - Powershell类方法返回被强制转换为新类型
- pandas - 通过字典将 pyspark 行列表转换为 pandas 数据框
- c++ - 如何使用 cmake 生成可运行的共享库
- typescript - 在 Typescript 中使用泛型强制执行相同的参数列表
- javascript - 如何更改制表器中特定列的列标题背景?(解决了)
- sql - 从雪花外部阶段选择行时如何使用正则表达式?
- java - AWS Kinesis 增强型扇出 Java 示例
- mongodb - mongodb高资源使用和配置提示
- json - aws cli 查询以查找最后拍摄的快照、拍摄日期、使用的标签(如果有)、实例的名称标签和实例 ID