【发布时间】: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(),但似乎没有发现任何区别。
谁能看出我做错了什么?
【问题讨论】: