我有一个圆环图设置,我想在标签上使用单击事件。使用此答案中的代码(https://stackoverflow.com/a/49118430/4611941 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;
这个包含图例中的标签。
如果您在 canvas 元素中传递一些选项,那么您也可以操纵 onClick 行为。
<canvas #chart baseChart
...
[options]="chartOptions">
</canvas>
在您的 .ts 文件中,您创建包含 onClick 行为的图表选项。这将覆盖默认行为。
例如,您可以使用其索引来汇总特定标签的值。
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';
这是修改后的代码。 https://stackblitz.com/edit/ng2-charts-doughnut-template-6aqyqu希望对您有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)