场景:在echars柱状图中,点击柱状图跳转到指定详情页面,我们可以直接使用api提供的方法,但是如果某些数值相对比较小,鼠标不能进入到柱状图区域,那就无法进行点击跳转。如下图:
处理方式:
1.使用echars提供的api方法:(这里使用双击charDblClick)
<div echarts class="chart-content" [options]="makeReqOrderOptions"
(chartDblClick)="onMoChartClick($event)">
</div>
- 使用getZr()代替原有点击事件。这是本文主要讲述的方式。
2.1 在html中定义id
<div id="mochartMain" echarts class="chart-content"
[options]="makeReqOrderOptions" ></div>
2.2 在ts中获取echars的dom,并添加点击事件,需要注意的是不能直接在oninit()方法中获取,需要settimeout,代码如下:
ngOnInit() {
setTimeout(() => {
this.loadMoChart();
});
}
/**
* 双击【订单&工单数据检查】柱状图
*/
loadMoChart() {
// 基于准备好的dom,初始化echarts实例
this.echarts = require('echarts');
// 只能初始化一次
if (this.myChart == null || this.myChart === undefined) {
const resource = this.el.nativeElement.querySelector('#mochartMain');
this.myChart = this.echarts.init(resource);
}
// 使用getZr()代替原有点击事件
this.myChart.off('dblclick'); // 防止触发两次点击事件
this.myChart.getZr().on('dblclick', params => {
const pointInPixel = [params.offsetX, params.offsetY];
if (this.myChart.containPixel('grid', pointInPixel)) {
const pointInGrid = this.myChart.convertFromPixel({
seriesIndex: 0
}, pointInPixel);
const xIndex = pointInGrid[0]; // 索引
const handleIndex = Number(xIndex);
const seriesObj = this.myChart.getOption(); // 图表object对象
// console.log(handleIndex, seriesObj);
// console.log(seriesObj.xAxis[0].data[handleIndex]);
// 获取柱状图标签名 seriesObj.xAxis[0].data[handleIndex],并跳转到详细页面
this.onMoChartClick(seriesObj.xAxis[0].data[handleIndex]);
}
});
}