You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ngx-pie-chart中实现图例hover触发对应扇区tooltip

ngx-pie-chart 自定义图例联动Tooltip实现方案

不用去DOM里找关联标识,直接通过组件API和数据关联就能实现,步骤如下:

1. 获取饼图组件实例

通过ViewChild获取PieChartComponent的实例,用来调用tooltip控制方法。

2. 给自定义图例项绑定鼠标事件

在每个图例项上添加mouseenter和mouseleave事件,传递对应的数据项。

3. 调用组件内置的Tooltip方法

利用组件自带的showTooltip和hideTooltip方法,实现鼠标悬停图例时显示对应扇区的Tooltip,离开时隐藏。

代码示例

组件类代码

import { Component, ViewChild } from '@angular/core';
import { PieChartComponent } from '@swimlane/ngx-charts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild(PieChartComponent) pieChart!: PieChartComponent;
  // 饼图数据
  chartData = [
    { name: '分类A', value: 40, color: '#3366cc' },
    { name: '分类B', value: 25, color: '#dc3912' },
    { name: '分类C', value: 35, color: '#ff9900' }
  ];

  // 鼠标进入图例项时触发
  onLegendHoverEnter(item: any) {
    // 匹配对应扇区的series数据
    const targetSeries = this.pieChart.series.find(series => series.name === item.name);
    if (targetSeries) {
      // 调用showTooltip显示对应Tooltip,第二个参数为数据索引(饼图固定为0)
      this.pieChart.showTooltip(targetSeries, 0);
    }
  }

  // 鼠标离开图例项时触发
  onLegendHoverLeave() {
    this.pieChart.hideTooltip();
  }
}

模板代码

<!-- 自定义图例 -->
<div class="custom-legend">
  <div 
    *ngFor="let item of chartData"
    (mouseenter)="onLegendHoverEnter(item)"
    (mouseleave)="onLegendHoverLeave()"
    class="legend-item"
  >
    <span class="legend-dot" [style.backgroundColor]="item.color"></span>
    <span>{{ item.name }}</span>
  </div>
</div>

<!-- ngx饼图组件 -->
<ngx-pie-chart
  [view]="[600, 350]"
  [data]="chartData"
  [labels]="true"
  [tooltipDisabled]="false"
></ngx-pie-chart>

补充说明

  • 核心逻辑是通过数据的name字段匹配饼图内部的series集合,不需要操作DOM查找关联元素,避免DOM结构变化导致的兼容问题。
  • 不同版本的ngx-charts可能对showTooltip的参数要求略有差异,若调用失败可参考组件源码或官方文档调整参数。

内容的提问来源于stack exchange,提问作者iamcootis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:35:16