【问题标题】:How to unregister chartjs-plugin-datalabels globally?如何在全球范围内注销 chartjs-plugin-datalabels?
【发布时间】:2020-03-05 14:15:29
【问题描述】:

我正在尝试根据全局注销 chartjs 插件 https://chartjs-plugin-datalabels.netlify.com/guide/getting-started.html#registration

我的 Angular 应用结构

布局---->

module a---> lazy loaded
      component a1---> chart js chart

module b ----> lazy loaded 
      component b1---> chart js chart
module c---->lazy loaded

这些组件从 .ts 文件中获取我的选项

我用的是普通的ts文件

我的 .ts 文件

import ChartDataLabels from "chartjs-plugin-datalabels";

Chart.plugins.unregister(ChartDataLabels);
// a function which return chart options to component
get myChartOptions()
{
var options = new Options();  //my class
let plugin = options.getPlugin();  //another .ts file which assign value
return options;
}

Expected: Chartjs Data Plugin will get unregistered itself at load.
Actual:   Plugin is not getting itself unregistered. Datalabels are 
          being in on component change also.

How to globally unregister the plugin in .ts file ??

【问题讨论】:

    标签: angular charts


    【解决方案1】:

    我找到的唯一解决方案是在图表的每个实例上禁用它。 https://www.chartjs.org/docs/latest/developers/plugins.html#disable-plugins

    例子:

    options: {
        plugins: {
            p1: false   // disable plugin 'p1' for this instance
        }
    }
    

    【讨论】:

    • 这是官方推荐的方式。然而,类型可能没有正确声明为 ts (Type 'false' has no properties in common with type '_DeepPartialObject<PluginOptionsByType<"line">>)
    • 在某些插件中有启用选项,因此您可以将代码更改为:plugins: { pluginName: { enable: false } }
    【解决方案2】:

    在您的顶级文件导入中:

    ChartDataLabels from "chartjs-plugin-datalabels"
    Chart from "chart.js"
    

    现在禁用插件:

    Chart.plugins.unregister(ChartDataLabels);
    

    我使用 React,这三行在我的 index.js 中的 render 方法之前。

    您现在可以通过添加到图表组件来本地启用插件:

    plugins={[ChartDataLabels]}

         <Pie 
                    type="pie"
                    data={data}
                    borderWidth="10"
                    plugins={[ChartDataLabels]}
                    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2020-07-11
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 2017-06-12
      相关资源
      最近更新 更多