【发布时间】:2021-03-11 14:24:28
【问题描述】:
【问题讨论】:
-
能否请您在此处发布您当前构建的所有代码,以便我们查看和使用您的代码?
-
您首先要阅读有关您使用的图表库的文档。
标签: javascript angular typescript charts echarts
【问题讨论】:
标签: javascript angular typescript charts echarts
这实际上是 Apache ECharts 开箱即用的支持,只需更改图表选项即可。您想将tooltip.triggerOn 设置为'click' 而不是'mousemove'。例如:
const options = {
/* ... other options ... */
tooltip: {
show: true,
trigger: "axis",
triggerOn: "click",
}
}
您希望在单击/显示时从工具提示中获取值。为此,我们使用events 并向showTip 事件添加回调。
chart.on("showTip", console.log);
我不会做太多 Angular,所以这可能不是最好的代码,但它可以工作!
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;
}
}
【讨论】: