【问题标题】:Angular: chart.js chart is not displayingAngular:chart.js 图表未显示
【发布时间】:2020-04-26 16:12:05
【问题描述】:

我正在使用 Angular,我已经安装了 chart.js,但图表没有显示在页面中。

这是我的代码:

dasboard.component.html

<canvas id="myChart" width="400" height="400"></canvas>

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js'

@Component({
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

    ngOnInit() {
        var myChart = new Chart('myChart', {
            type: 'bar',
            data: {
                labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                datasets: [{
                    label: '# of Votes',
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    }
}

当我这样做时

console.log('hello');

dashboard.component.ts 中,它正在控制台中打印,但图表没有显示我该如何解决这个问题?

【问题讨论】:

标签: angular chart.js


【解决方案1】:

您的代码很好,只需将canvas 包含到div 中,它就会显示出来。

<div>
  <canvas id="myChart" width="400" height="400"></canvas>
</div>

请看下面StackBlitz

【讨论】:

    猜你喜欢
    • 2014-09-11
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多