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

Angular+PrimeNG+Chart.js更新图表触发意外滚动问题求助

问题:Angular + PrimeNG Chart.js 更新时自动滚动到可视区域外的图表

我正在开发一个使用PrimeNG和Chart.js的Angular应用,页面包含大量表单与图表。更新表单字段时需同步更新对应图表,整体功能正常,但当图表处于屏幕可视区域外时,更新字段会触发图表更新,同时页面会自动滚动至该图表位置,给用户继续填写表单带来困扰。

图表配置项

{
    indexAxis: "y",
    animation: false,
    aspectRatio: 0.2,
    maintainAspectRatio: false,
    scales: {
        x: {
            axis: "x",
        },
        y: {
            axis: "y",
        }
    },
    x: {
        beginAtZero: true,
        stacked: true
    },
    y: {
        beginAtZero: true,
        stacked: true
    },
    cutout: "50%",
    plugins: {
        title: {
            color: "gray",
            font: {
                weight: "bold",
                size: 12
            }
        },
        legend: {
            display: false,
            position: "top"
        },
        datalabels: {
            color: "white",
            align: "center",
            anchor: "center",
            textAlign: "center",
            formatter: (val: number, ctx: Context): string => {
              if (val) {
                const label = ctx.chart.data.labels[ctx.datasetIndex] as string;
                const value = ctx.chart.data.datasets[ctx.datasetIndex].data[0];
                return `${label} (${value})`;
              }
              return '';
            },
        },
        tooltip: {
            enabled: true,
            callbacks: {
              title: (): string => '',
              label: (tooltipItem: any): string => {
                const { chart } = tooltipItem;
                const label = chart.data.labels[tooltipItem.datasetIndex];
                const value: number = chart.data.datasets[tooltipItem.datasetIndex].data[0];
                return `${label}: ${value}`;
              },
            },
        },
    },
}

HTML模板使用方式

<p-chart type="bar" [data]="data" [plugins]="barChartPlugins"
  [options]="options" width="280px" height="80px" />

已尝试的无效方案

  • 添加以下Chart.js配置项,无效果:
interaction: {
   mode: undefined,
   intersect: false,
},
transitions: {
   active: { animation: { duration: 0 } },
   show: { animation: { duration: 0 } },
   hide: { animation: { duration: 0 } },
},
  • 通过指令将图表元素的tabindex设为-1,指令生效但问题依旧

额外发现的现象

  • 页面结构:PageComponent包含HeaderComponent和ContentComponent两个子组件,表单位于ContentComponent中,图表同时存在于HeaderComponent和ContentComponent中
  • 移除ContentComponent中的图表后,即使HeaderComponent中的图表更新,也不会出现自动滚动问题

请问有什么解决该问题的思路吗?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:42:07