Chart.js annotations working but causing console error in Angular 5

1.5k Views Asked by At

I have a dynamic chart generating component based on the data that is received. I create a chart instance inside the component and fill out the properties. I imported the chartjs-annotate-plugin as

import * as annotation from 'chartjs-plugin-annotation'; 

and register the chart plugin like so:

constructor() {
   Chart.pluginService.register(annotation);
} 

I tried to move this right before the chart instantiation, but what's funny is that while I do see the annotation, it also causes a console error saying that annotate is not a property on ChartOptions:

ERROR in src/app/shared/charts/chart/chart.component.ts(143,11): error 
  TS2345: Argument of type '{ plugins: any[]; type: string; data: { labels: 
  any[]; datasets: any[]; }; options: { scales: { y...' is not assignable to 
  parameter of type 'ChartConfiguration'.
  Types of property 'options' are incompatible.
  Type '{ scales: { yAxes: { stacked: boolean; ticks: { beginAtZero: true; 
  callback: (value: any, index: ...' is not assignable to type 
 'ChartOptions'.
Object literal may only specify known properties, and 'annotation' does 
not exist in type 'ChartOptions'.

Any ideas?

Edit from bountier: This is not the OP's code, but here is some code that reproduces the problem in Angular 8 and ChartJS Annotation plugin 0.5.7:

let annotation = [];

annotation.push({
        drawTime: 'beforeDatasetsDraw',
        type: 'box',
        xMin: i - 1, //index + 1,
        xMax: i + 1, //index + 5,
        yMin: this.yValues.reduce((a, b) => Math.min(a, b)).toString(),
        yMax: this.yValues.reduce((a, b) => Math.max(a, b)).toString(),
        // ID of the X scale to bind onto
        xScaleID: 'x-axis-0',

        // ID of the Y scale to bind onto
        yScaleID: 'y-axis-0',
        backgroundColor: 'rgba(101, 33, 171, 0.15)',
        borderColor: 'rgba(101, 33, 171, 0.5)',
        borderWidth: 2,
      });

let namedChartAnnotation = ChartAnnotation;
Chart.pluginService.register(namedChartAnnotation);

return new Chart('histogram' + number, {
  type: 'bar',
  data: {
    labels: this.xValues,
    datasets: [
      {
        label: 'Number of alerts',
        data: this.yValues,
      },
    ],
  },
  options: {
     annotation: {
        annotations: annotation,
     }
  }
});

With this code, I get the error specified above in the console, but it works as expected otherwise. If I move the annotation: part to plugins:, the error disappears, but the annotations no longer show up at all:

....
options: {
   plugins: {
      annotation: {
         annotations: annotation,
      },
   }
}
0

There are 0 best solutions below