首页 > 解决方案 > 如何在 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]。

有人知道为什么没有创建图表吗?

标签: angularchart.js

解决方案


我通常通过primeng使用chart.js,即使我不想使用primeng,我也会效仿他们,因为我觉得它很干净。你可以在这里看到他们是如何实现它的:https ://github.com/primefaces/primeng/blob/master/src/app/components/chart/chart.ts


推荐阅读