首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ng2-charts中动态使用chartjs-plugin-annotation?

如何在ng2-charts中动态使用chartjs-plugin-annotation?
EN

Stack Overflow用户
提问于 2019-05-20 18:00:14
回答 1查看 1.3K关注 0票数 4

我正在创建一个统计页面,其中我需要显示几个图表,我在这里(https://valor-software.com/ng2-charts/#DynamicChart)创建了一个涵盖了演示中的条形图和折线图的DynamicChartComponent。其中一个图表需要显示数据集的平均注释。为此,我使用chartjs-plugin-annotation,其配置如下:

代码语言:javascript
复制
{
    responsive: true,
    scales: {
      xAxes: [{}],
      yAxes: [
        {
          id: 'y-axis-0',
          position: 'left',
        }
      ]
    },
    annotation: {
        drawTime: "afterDatasetsDraw",
        annotations: [
            {
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y-axis-0',
            value: 0, // Average must be filled here
            borderColor: 'red',
            borderWidth: 2
            },
        ]
    },
}

与数据集值不同,注释不会在值更改时更新,因此我尝试使用ViewChield装饰器手动更新图表。

DynamicChartComponent.ts:

代码语言:javascript
复制
import { Component, Input, Output, EventEmitter, OnInit, ViewChild } from '@angular/core';
import { DynamicChart } from '../../libs/classes/dynamicChart';
import { ChartDataSets, ChartOptions, ChartType } from 'chart.js';
import { Label, BaseChartDirective } from 'ng2-charts';
import * as pluginAnnotations from 'chartjs-plugin-annotation';

@Component({
  selector: 'dynamic-chart',
  templateUrl: 'dynamic-chart.html'
})
export class DynamicChartComponent implements OnInit {
  @ViewChild(BaseChartDirective) chart: BaseChartDirective;

  private mychart = new DynamicChart();

  constructor() {}
  ngOnInit(){
    console.log("_chart", this.chart);
  }
  setAnnotation(value){
    this.mychart.options.annotation.annotations[0].value = value;
    //this.chart.update()
  }

DynamicChartComponent.html内幕

代码语言:javascript
复制
<canvas baseChart *ngIf="datasets"
    [datasets]="datasets" 
    labels]="labels"
    [chartType]="chartType"
    [legend]="legendVisible"
    [options]="options"
</canvas>

统计页面上的预期使用情况:

代码语言:javascript
复制
private myDynamicChart = new DynamicChartComponent();
myDynamicChart.setAnnotation(averageValue);
myDynamicChart.update();

我发现ViewChild装饰器产生了这个错误:

代码语言:javascript
复制
Object(...) is not a function

我在这里做错了什么?

其他问题的答案提到了ng2-charts-x的使用,但这并没有解决我的问题。

EN

回答 1

Stack Overflow用户

发布于 2020-12-11 02:36:03

我今天遇到了这个问题,并通过打电话解决了这个问题:

代码语言:javascript
复制
this.chart.ngOnChanges({});

而不是

代码语言:javascript
复制
this.chart.update()

ngOnChanges调用会导致图表更新并显示我以编程方式添加的注释,而在调用update时,它们根本不会显示。希望这能帮助任何在这个问题上遇到困难的人。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56218539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档