Angular 12 + Chartjs 3.3.2 类型错误:无法读取属性'left'



在学习角度时遇到了一个小障碍。我想显示我从api中获得的数据。但目前,我已经尝试创建一个具有预定义值的图表,稍后我会将其更改为get响应值。这是我采取的步骤:

  • npm安装chart.js
  • 查看图表组件.html<div width="100%"><canvas id="myChartTest" width="400" height="400"></canvas></div>
  • 查看图表组件.ts
import { Chart, LineController, LineElement, PointElement, LinearScale, Title } from 'chart.js';
Chart.register(LineController, LineElement, PointElement, LinearScale, Title);
Component({
selector: 'app-view-chart',
templateUrl: './ViewChart.component.html',
styleUrls: ['./ViewChart.component.scss']
})
export class ViewChartComponent implements OnInit {
ngAfterViewInit() {
var myChart = new Chart('myChartTest', {
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: {
y: {
beginAtZero: true
}
}
}
});
}

编译该项目时没有任何错误。但当我看到它时,我会得到这些错误

错误类型错误:无法读取未定义的属性"left"位于_isPointInArea(helpers.segment.js:1278(查特_handleEvent(chart.esm.js:5876(查特_eventHandler(chart.esm.js:5855(在listener(chart.esm.js:5738(在Chart.event(Chart.esm.js:3083(在helpers.segment.js:28计时器(zone.js:2561(位于ZoneDelegate.invokeTask(zone.js:406(位于Object.onVokeTask(core.js:28654(在ZoneDelegate.invokeTask(zone.js:405(

core.js:6456错误类型错误:无法读取未定义的属性"left"位于_isPointInArea(helpers.segment.js:1278(在getNearestItems(chart.esm.js:2523(最接近(chart.esm.js:2609(在Chart.getElementsAtEventForMode(Chart.esm.js:5621(查特_handleEvent(chart.esm.js:5872(查特_eventHandler(chart.esm.js:5855(在listener(chart.esm.js:5738(在Chart.event(Chart.esm.js:3083(在helpers.segment.js:28在定时器(zone.js:2561(

问题似乎出在您导入Chart的过程中。您正在尝试显示bar图表,但该图表尚未导入。您还需要导入BarElement。测试图表是否被渲染的较短方法是只导入以下内容:

import Chart from 'chart.js/auto';

您可以参考chart.js文档的集成部分来了解可能缺少的内容,或者这里有一个示例stackblitz。

最新更新