Angular 9 - ошибка аннотации chartjs-plugin-annotation

Я пытаюсь провести вертикальную линию на своем ng2-chartsдиаграмма. Для этого я установил chartjs-plugin-annotationпакет. К сожалению, это не работает, и я не могу понять, что не так.

Моя конфигурация в основном такая же, как и здесь.

import { Input } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ChartDataSets, ChartOptions, ChartPoint } from 'chart.js';
import * as annotations from 'chartjs-plugin-annotation';
import { Color, Label } from 'ng2-charts';
import { STO } from 'src/app/models/STO';


    @Component({
      selector: 'app-sto-chart',
      templateUrl: './sto-chart.component.html',
      styleUrls: ['./sto-chart.component.css']
    })
    export class StoChartComponent implements OnInit {
    
      @Input() sto: STO;
      STOs: STO[];
      stoChartData = new Array<ChartDataSets>();
      stoChartLabels = new Array<Label>();
      // ***** HERE IS THE ISSUE **************************************
      stoChartOptions: (ChartOptions & { annotation?: any }) = {
        responsive: true,
        annotation: {
          annotations: [
            {
              type: 'line',
              mode: 'vertical',
              scaleID: 'x-axis-0',
              value: '2020-10-05',
              borderColor: 'red',
              borderWidth: 2,
              label: {
                content: 'TODAY',
                enabled: true,
                position: 'top'
              }
            }
          ]
        }
      }; 
    
      stoChartColors: Color[] = [
        {
          borderColor: 'black',
        },
      ];
      stoChartLegend = true;
      stoChartType = 'line';
      stoChartPlugins = [];
    
      constructor() {}
    
      ngOnInit(): void {
        // *** some code here ***
      } 
    
    }

Проблема в ChartOptions: я все время получаю эту ошибку:

Type '{ responsive: true; annotation: { annotations: { type: string; mode: string; scaleID: string; value: string; borderColor: string; borderWidth: number; label: { content: string; enabled: boolean; position: string; }; }[]; }; }' is not assignable to type 'ChartOptions & { annotation?: any; }'.
  Type '{ responsive: true; annotation: { annotations: { type: string; mode: string; scaleID: string; value: string; borderColor: string; borderWidth: number; label: { content: string; enabled: boolean; position: string; }; }[]; }; }' is not assignable to type 'ChartOptions'.
    The types of 'annotation.annotations' are incompatible between these types.
      Type '{ type: string; mode: string; scaleID: string; value: string; borderColor: string; borderWidth: number; label: { content: string; enabled: boolean; position: string; }; }[]' is not assignable to type 'AnnotationOptions[]'.
        Type '{ type: string; mode: string; scaleID: string; value: string; borderColor: string; borderWidth: number; label: { content: string; enabled: boolean; position: string; }; }' is not assignable to type 'AnnotationOptions'.
          Type '{ type: string; mode: string; scaleID: string; value: string; borderColor: string; borderWidth: number; label: { content: string; enabled: boolean; position: string; }; }' is not assignable to type 'LineAnnotationOptions'.
            Types of property 'type' are incompatible.
              Type 'string' is not assignable to type '"line"'.

Возможно, стоит отметить, что import * as annotations from 'chartjs-plugin-annotation';говорит, что объявлено "аннотации", но его значение никогда не читается.

2 ответа

Согласно документации ChartJS и ReadMe по аннотациям на Github, похоже, что плагин Annotations необходимо добавить к объекту "plugins" в объекте "ChartOptions".

Я бы попробовал что-то вроде этого:

stoChartOptions: (ChartOptions & { annotation?: any }) = {
    responsive: true,
    plugins: {
       annotation: {
          annotations: [
          {
            type: 'line',
            mode: 'vertical',
            scaleID: 'x-axis-0',
            value: '2020-10-05',
            borderColor: 'red',
            borderWidth: 2,
            label: {
              content: 'TODAY',
              enabled: true,
              position: 'top'
            }
          }
        ]
      }
    }
  }; 

Кроме того, вы импортируете * как аннотации. В этом контексте может потребоваться изменить это на аннотацию, поскольку первый элемент в массиве плагинов - это имя плагина.

https://www.chartjs.org/docs/latest/developers/plugins.html

https://github.com/chartjs/chartjs-plugin-annotation#readme

Думаю, я понял, в чем проблема. Проверьте ответ, который я дал на этот вопрос. Видимо, я был не единственным, у кого была проблема с ng2-charts.

Другие вопросы по тегам