在Angular和Chart.js中,出现错误类型错误:无法读取未定义的属性'15'通常是由于Chart.js版本与Angular中使用的版本不兼容引起的。下面是解决此问题的代码示例:
npm install chart.js --save
import * as Chart from 'chart.js';
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
@ViewChild('chartCanvas', { static: true }) chartCanvas: ElementRef;
private chart: Chart;
constructor() { }
ngOnInit() {
this.chart = new Chart(this.chartCanvas.nativeElement, {
type: 'line',
data: {
// chart data here
},
options: {
// chart options here
}
});
}
}
#chartCanvas
指令将其引用赋给组件的chartCanvas
变量:
这样就可以在Angular项目中正确地使用Chart.js库,并避免出现错误类型错误:无法读取未定义的属性'15'。请确保Chart.js库的版本与Angular版本兼容,并正确地初始化和配置图表实例。