我试图让 Chart.js 中的 onclick 函数正常工作,并发现 getElementsAtEvent(event)
函数应该返回一个包含图表部分数据的数组我点击了它,但它不断返回一个空数组。
这是我的代码:
var canvas = this.el; //this is an elementref
canvas.onclick = (event) => {
var data = this.chart.getElementsAtEvent(event)
console.log(data);
}
this.chart = new Chart('canvas', {
type: 'bar',
data: {
labels: ["Browser", "Game", "Word Processing", "Database", "Spreadsheet", "Multimedia"],
datasets: [{
label: 'number of applications related to',
data: [24, 10, 30, 20, 46, 78],
backgroundColor: 'rgba(54, 162, 235, 0.2',
borderColor: 'rgba(54, 162, 235, 1)',
pointHoverBackgroundColor: 'red',
borderWidth: 1
}]
},
options: {
title: {
text: "Application Logs",
display: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
不确定这是否是它不起作用的部分原因,但这是我的 Canvas :
<canvas id="canvas" width="300" height="123" class="chartjs-render-monitor"></canvas>
就像我提到的,它只是在控制台中打印出一个空数组 [],而使用 console.log(data[0])
显然只是返回 undefined。
最佳答案
下面的代码对我有用,而且不需要使用 ElementRef
添加点击事件处理程序。您只需调用 (click)
上的方法即可事件<canvas>
像下面这样-
<canvas id="canvas" width="300" height="123" #mychart (click)="showData($event)" class="chartjs-render-monitor">{{chart}}</canvas>
这里我使用 chart
渲染了图表。组件的属性。
这是 showData()
方法-
showData(evt:any){
var data = this.chart.getElementsAtEvent(evt)
console.log(data[0]._model); // it prints the value of the property
}
这是完整的工作代码-
app.component.ts
import { Component,ViewChild,ElementRef,OnInit } from '@angular/core';
import Chart from 'chart.js';
declare var Chart: any;
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit{
name = 'Angular 5';
chart:any;
// @ViewChild('mychart') el:ElementRef;
constructor(){
}
ngOnInit(){
this.createChart();
}
createChart(){
// var canvas = this.el;
this.chart = new Chart('canvas', {
type: 'bar',
data: {
labels: ["Browser", "Game", "Word Processing", "Database", "Spreadsheet", "Multimedia"],
datasets: [{
label: 'number of applications related to',
data: [24, 10, 30, 20, 46, 78],
backgroundColor: 'rgba(54, 162, 235, 0.2',
borderColor: 'rgba(54, 162, 235, 1)',
pointHoverBackgroundColor: 'red',
borderWidth: 1
}]
},
options: {
title: {
text: "Application Logs",
display: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
showData(evt:any){
var data = this.chart.getElementsAtEvent(evt)
console.log(data[0]._model);
}
}
app.component.html
<canvas id="canvas" width="300" height="123" #mychart (click)="showData($event)" class="chartjs-render-monitor">{{chart}}</canvas>
这是一个工作演示 - https://stackblitz.com/edit/angular-5-example-txcthz
关于Angular 5 Chart.js onclick 返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607215/