This is actually supported by Apache ECharts out of the box just by changing your chart options. You want to set tooltip.triggerOn to 'click'
instead of 'mousemove'
. For example:
const options = {
/* ... other options ... */
tooltip: {
show: true,
trigger: "axis",
triggerOn: "click",
}
}
You want to get the value from the tooltip when it is clicked/shown. For that we use events and add a callback to the showTip
event.
chart.on("showTip", console.log);
I don't do much Angular so this might not be the best code, but it works!
import { Component } from "@angular/core";
import { init, ECharts, EChartOption } from "echarts";
@Component({
selector: "app-root",
template: `
<div id="echarts-container" #chartContainer>
Content
</div>
`,
// needs a minimum height
styles: ["#echarts-container { height: 100vh; }"]
})
export class AppComponent {
private chart?: ECharts;
ngOnInit() {
// I bet there is a more angular-specific way to access the element
const chartContainer = document.getElementById("echarts-container");
if (chartContainer instanceof HTMLDivElement) {
this.initializeChart(chartContainer);
} else {
throw new Error("invalid element");
}
}
ngOnDestroy() {
this.chart?.dispose();
}
private doSomethingWithTooltipValue(value: number, label: string) {
// we've got access -- now what do you want to do?
console.log(`activated tooltip with label: ${label} and value: ${value}`);
}
private initializeChart(element: HTMLDivElement) {
const option: EChartOption = {
// some example data
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
},
yAxis: {
type: "value"
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: "line"
}
],
// show the tooltip on click
tooltip: {
show: true,
trigger: "axis",
triggerOn: "click"
}
};
const chart = init(element);
chart.setOption(option);
chart.resize();
chart.on("showTip", ({ dataIndex, seriesIndex }) => {
// TODO: would need to be more specific about the data types in order to lookup like this
const label = option.xAxis.data[dataIndex];
const value = option.series[seriesIndex].data[dataIndex];
this.doSomethingWithTooltipValue(value, label);
});
// save chart instance to component so we can dispose of it in ngOnDestroy
// there might be a more angular-specific way to do this
this.chart = chart;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.