angular - 图表点击事件 - 点击圆环图的标签,不返回标签 ng2-charts
问题描述
我有一个圆环图设置,我想在标签上使用点击事件。使用此答案中的代码(https://stackoverflow.com/a/49118430/4611941),我可以在单击图表以返回标签和数据时触发单击事件:
chartClicked (e: any): void {
debugger;
if (e.active.length > 0) {
const chart = e.active[0]._chart;
const activePoints = chart.getElementAtEvent(e.event);
if ( activePoints.length > 0) {
// get the internal index of slice in pie chart
const clickedElementIndex = activePoints[0]._index;
const label = chart.data.labels[clickedElementIndex];
// get value by index
const value = chart.data.datasets[0].data[clickedElementIndex];
console.log(clickedElementIndex, label, value)
}
}
}
当返回标签时单击图表数据本身时,这非常有效,然后我可以使用此值。但是,当单击图表上方的标签本身时,此代码无法获取单击的标签的值(e.active.lenth = 0)。但是,它仍然通过将该标签的数据删除/添加到圆环图来执行过滤。
这就是我目前的图表设置方式:
<canvas #chart baseChart
[data]="doughnutChartData"
[labels]="doughnutChartLabels"
[chartType]="doughnutChartType"
(chartClick)="chartClicked($event)"
[colors]="chartColors">
</canvas>
是否可以通过单击圆环图的标签来获取标签的值并防止对图表进行过滤操作?
解决方案
您可以通过@ViewChild 访问您的图表。您已经在 HTML 中设置了本地引用。
@ViewChild(BaseChartDirective) chart: BaseChartDirective;
这个包含图例中的标签。
如果您在画布元素中传递一些选项,那么您也可以操纵 onClick 行为。
<canvas #chart baseChart
...
[options]="chartOptions">
</canvas>
在您的 .ts 文件中,您创建包含 onClick 行为的 chartOptions。这将覆盖默认行为。例如,您可以使用其索引来总结特定标签的值。
public chartOptions: ChartOptions = {
legend: {
onClick: (e, i) => {
console.log(this.chart.data[i.index].reduce((total, next) => total+next));
}
}
}
不要忘记导入
import { ..., ChartOptions } from 'chart.js';
import { ..., BaseChartDirective } from 'ng2-charts';
这是修改后的代码。 希望对您有所帮助。
推荐阅读
- python - 每当我尝试执行命令 python manage.py runserver 或 python manage.py shell 时,我都在处理 DjangoRest 项目它不会工作
- javascript - 尝试设置 Struct 的属性时出现 TypeError(Nashorn,Kafka Connect 转换器)
- javascript - 为什么在 laravel 的 foreach 循环内部视图中使用按钮元素不起作用?
- amazon-web-services - 通过 Cloudformation 和 OAI 访问 S3 存储桶时的 NoSuchKey 和 HTTP 404
- spring - 刷新物化视图(非同时)以“没有剩余空间”错误结束
- java - 如何将库导入 Netbeans IDE
- laravel - Laravel Scout - 不等于
- c++ - C ++尝试插入排序失败?
- javascript - 再次单击时如何使该功能再次运行?
- reactjs - 如何更改 React-Admin 过滤器