javascriptangularchart.jsng2-charts

Applying custom plugins to specific charts in Chart.js (not globally)


I have 3 charts on a component in my angular app.

I need to create text label plugins to show on the chart. Each chart needs to have specific plugin assigned to it. I have searched a lot and could not find any solution. As of now i am registering the plugins globally with Chart.register() which is making the appearance undesirable because all of the label plugins gets applied to all of the charts.

is there any way to apply specific plugins to specific charts?

I am using ng2-charts and defining my charts like with BaseChartDirective.

@ViewChildren(BaseChartDirective) charts?: QueryList<BaseChartDirective>;

I am creating plugins like this

function createLabelPlugin(text: string, xPosition: number, yPosition: number) {
  return {
    id: 'customLabelPlugin',
    afterDraw(chart: any) {
      const ctx = chart.ctx;
      ctx.save();
      ctx.font = 'bold 16px Arial';
      ctx.fillStyle = 'black';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      // Draw the text at the specified position
      ctx.fillText(text, xPosition, yPosition);

      ctx.restore();
    }
  };
}

Solution

  • The ng2-charts has library has an @Input parameter named plugins where you can supply the plugin that you want to set for a particular chart.

    base-chart.directive.ts

    export class BaseChartDirective<
        TType extends ChartType = ChartType,
        TData = DefaultDataPoint<TType>,
        TLabel = unknown,
      >
      implements OnDestroy, OnChanges
    {
      ...
      @Input() public plugins: Plugin<TType>[] = [];
    

    To use it, just add the plugin as below.

    TS:

    export class LineComponent {
      plugins = [createLabelPlugin('qwerty', 0, 0)];
    

    HTML:

    <canvas baseChart [type]="chartType" [data]="data" [options]="options" [plugins]="plugins">
    </canvas>
    

    Stackblitz Demo

    if you are dealing with data labels, I recommend chartjs-plugin-datalabels, great for displaying labels on charts.