Table of contents
1. Requirements description:
Click the icon of the pie chart, and the total number in the middle of the pie chart will change dynamically with the selected icon.
2. Implementation method:
// 切换图例选中状态后的事件
chart.on('legendselectchanged', function (obj) {}
Official Documentation: Documentation - Apache ECharts
3. Angular implementation:
ChartsChange() {
let thisOption = this.option;
let thisEchartsInstance = this.echartsIntance;
// 解决重复触发
thisEchartsInstance.off("legendselectchanged");
// 切换图例选中状态后的事件
thisEchartsInstance.on("legendselectchanged", function (params) {
let total = 0;
const legendSelectedArr = {};
thisOption?.data?.forEach(element => {
// 获取图例的选中状态,并存储在 legendSelectedArr 对象中,用于后面 计算总数判断 和 updateOption
legendSelectedArr[element.name] = params.selected[element.name];
// 计算被选择的总数
if (params.selected[element.name]) {
total += element.value;
}
});
// 赋值总数
thisOption.graphic.elements[0].style.text = total;
// 赋值状态,否则更新option后,图例的选中状态会失效
thisOption.legend.selected = legendSelectedArr;
thisEchartsInstance.setOption(thisOption, true);
});
}
<!-- 饼图 -->
<div
echarts
[options]="option"
(chartInit)="onChartInitPie($event)"
(click)="ChartsChange()"
></div>
4. Problem description:
The pie chart click legend event does not respond for the first time, and only executes for the second time
Cause Analysis:
I think it is the first click, the click method is not registered by the chart instance object
5. Solution:
When the chart is initialized, call the click event method
onChartInitPie(ec: any) {
this.echartsIntance = ec;
this.updateEchartsIntanceOption();
// chart 初始化的时候也初始化方法,否则方法第一次触发失效
this.ChartsChange();
}