我在使angular Charts.js在对话框上工作时遇到问题。首先,我遵循了此链接中提供的步骤https://coursetro.com/posts/code/126/Let的-build-an-Angular-5-Chart.js-App --- Tutorial,它是为Angular 5设计的。我只是复制了测试数据到我的角度类数组。运行应用程序时,对话框为空白。我找到了关于Charts.js的另一个链接,即https://dev.to/wiaio/implementing-a-chartjs-line-chart-in-your-angular-application-19d7。我所做的更改是
HTML
<div *ngIf="chart">
<canvas id="canvas">{{chart}}</canvas>
</div>
to
<canvas #dataChart>{{ chart }}</canvas>
以我的ts代码
我添加了以下内容
export class ChartComponent implements OnInit {
@ViewChild('dataChart') private chartRef
chart: any;
ngOnInit() {
var temp_max = [279.946, 282.597, 280.15];
var temp_min = [279.946, 282.597, 278.15];
var alldates = [1485717216, 1485745061, 1485768552];
let weatherDates = []
let jsdate1 = new Date(1485717216 * 1000);
weatherDates.push(jsdate1.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }));
let jsdate2 = new Date(1485745061 * 1000);
weatherDates.push(jsdate2.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }));
let jsdate3 = new Date(1485768552 * 1000);
weatherDates.push(jsdate3.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }));
this.chart = new Chart(this.chartRef.nativeElement, {
type: 'line',
data: {
labels: weatherDates,
datasets: [
{
data: temp_max,
borderColor: "#3cba9f",
fill: false
},
{
data: temp_min,
borderColor: "#ffcc00",
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
}
}
});
}
我刚要离开时放置了一个断点并检查了this.chart,当我将鼠标悬停在this.chart上时,内容如下。我更改了几次代码。我什至将图表声明更改为chart:Chart,但它不起作用。在线示例看起来很简单,但是我可以追溯到导致空白对话框的错误。
感谢您对大师的任何帮助。谢谢。
_bufferedRender:假 _listeners:Object {mousemove:,mouseout:,单击:,…} $ plugins:Object {descriptors:Array(3),id:3}动画:true AspectRatio:2个框:Array(4)[ChartElement,ChartElement, ChartElement,…] canvas:canvas.chartjs-render-monitor {$ chartjs: __zone_symbol__mousemovefalse对象:Array(1), __zone_symbol__mouseoutfalse:Array(1),…}图表:图表{id:1,ctx:CanvasRenderingContext2D,canvas:canvas.chartjs-render-monitor,…} chartArea:Object {左:71.7158203125,上:6,右:-71.7158203125, …} config:Object {类型:“行”,数据:对象,选项:对象} 控制器:图表{id:1,ctx:CanvasRenderingContext2D,画布: canvas.chartjs-render-monitor,…} ctx:CanvasRenderingContext2D {canvas:canvas.chartjs-render-monitor,globalAlpha:1, globalCompositeOperation:“ source-over”,…} currentDevicePixelRatio:1 数据:对象高度:0 id:1 lastActive:Array(0)[]图例:ChartElement {ctx:CanvasRenderingContext2D,选项:对象,图表:图表,...}
答案 0 :(得分:1)
您遇到的问题是chartRef未定义。您可以使用
<canvas id=chart> in your html
并在Chart构造函数中使用chart,或使用setter:
chartRef;
@ViewChild('dataChart') set ref(ref: ElementRef) {
this.chartRef = ref;
}
我在#14的Stackblitz中制作了一个工作示例,该组件是图表示例
希望有帮助