我对Angular很陌生,这是我用Angular开发的第一个页面。我正在尝试在ChartJS条形图中实现onClick功能。
当我尝试在ChartJS的onClick中访问this.chart
时遇到此错误,
Property 'chart' does not exist on type '_DeepPartialObject<CoreChartOptions<"bar"> & ElementChartOptions<"bar"> & PluginChartOptions<"bar"> & DatasetChartOptions<"bar"> & ScaleChartOptions<...> & BarControllerChartOptions>'.ts(2339)
下面是我的代码:
图形.组件.html
<div class="chart-container">
<canvas id="canvas">{{ chart }}</canvas>
</div>
图形.组件.ts:
import { Inject, Injectable, Component, OnInit } from '@angular/core';
import {Chart, ChartConfiguration, ChartItem, registerables} from 'chart.js';
@Component({
selector: 'app-graphs',
templateUrl: './graphs.component.html',
styleUrls: ['./graphs.component.scss']
})
export class AssessmentGraphsComponent implements OnInit
{
constructor() { }
chart: any;
if(this.chart)
{
this.chart.destroy();
}
Chart.register(...registerables);
this.chart = new Chart('canvas', {
type:'bar',
data:
{
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
datasets: [
{
label: 'Something 1',
backgroundColor: 'lightblue',
borderColor: 'rgb(255, 99, 132)',
data: [1, 1, 3, 5, 2]
},
{
label: 'Something 2',
backgroundColor: 'green',
borderColor: 'rgb(255, 99, 132)',
data: [1,2,3,4,5]
},
{
label: 'Something 3',
backgroundColor: 'blue',
borderColor: 'rgb(255, 99, 132)',
data: [3,4,5,1,2]
},
]
},
options:
{
responsive: true,
scales:
{
x: {display: true},
y: {beginAtZero: true, display: true, ticks: {precision: 0}}
},
events: ['click'],
onClick: function(e)
{
console.log("CLICKED"); // This is working
// This line shows this error:
// Property 'chart' does not exist on type '_DeepPartialObject<CoreChartOptions<"bar"> & ElementChartOptions<"bar"> & PluginChartOptions<"bar"> & DatasetChartOptions<"bar"> & ScaleChartOptions<...> & BarControllerChartOptions>'.ts(2339)
const points = this.chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
if (points.length)
{
const firstPoint = points[0];
const label = this.chart.data.labels[firstPoint.index];
const value = this.chart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
}
}
}
});
我使用的代码如下:
https://www.chartjs.org/docs/latest/developers/api.html#getelementsateventformode-e-mode-options-usefinalposition
有人能帮我一下吗,谢谢。
1条答案
按热度按时间mcdcgff01#
您可以使用onClick侦听器中的第三个参数来避免此问题,该参数已经是chartInstance: