【问题标题】:Chart.js chart doesn't render when using Angular 2 [duplicate]使用 Angular 2 时 Chart.js 图表不呈现 [重复]
【发布时间】:2016-09-01 17:00:44
【问题描述】:

我正在尝试在一个用 typescript 编写的 Angular2 应用程序中使用 Chart.js 2.0。首先,我一直在尝试使文档中显示的基本图表正常工作(请参阅http://www.chartjs.org/docs/#getting-started-creating-a-chart),但运气不佳。我的图表对象已创建但从未在浏览器中呈现。

我的组件如下所示:

import {Component,  Input, AfterViewInit, NgZone} from 'angular2/core';


declare var Chart;

@Component({
    selector: 'chart',
    templateUrl: '/app/components/chart.template.html'
})


export class ChartComponent implements AfterViewInit {

    constructor(private zone: NgZone) { }

    ngAfterViewInit() {
        console.log('In the after function')
        this.zone.runOutsideAngular(() => {
            var ctx = document.getElementById("myChart");
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                    datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3]
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
            console.log(myChart);
        });

    }
}

我的模板很简单,只有一行设置画布:

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

我可以从我的日志语句中看到正在创建图表对象并且使用正确的数据,它只是从未出现在浏览器中呈现。当我在 Firebug 中查看源代码时,我看到:

<chart>
   <iframe style="width: 100%; display: block; border: 0px none; height: 0px; margin: 0px; position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px;" class="chartjs-hidden-iframe"></iframe>
   <canvas style="width: 0px; height: 0px;" width="0" id="myChart" height="0"></canvas>
</chart>

我尝试添加 myChart.render()myChart.draw(),但似乎没有发现任何区别。

谁能看出我做错了什么?

【问题讨论】:

标签: angular chart.js


【解决方案1】:

我不会在这里使用区域,而是使用类似的东西:

export class ChartComponent implements AfterViewInit {
  @ViewChild('myChart')
  myChart:ElementRef;

  ngAfterViewInit() {
    var myChart = new Chart(this.myChart.nativeElement, {
    (...)
  }
}

在模板中:

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

这个问题也可以帮助你:

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 2018-02-09
    • 2017-12-29
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多