我正在创建一个统计页面,其中我需要显示几个图表,我在这里(https://valor-software.com/ng2-charts/#DynamicChart)创建了一个涵盖了演示中的条形图和折线图的DynamicChartComponent。其中一个图表需要显示数据集的平均注释。为此,我使用chartjs-plugin-annotation,其配置如下:
{
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:
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内幕
<canvas baseChart *ngIf="datasets"
[datasets]="datasets"
labels]="labels"
[chartType]="chartType"
[legend]="legendVisible"
[options]="options"
</canvas>统计页面上的预期使用情况:
private myDynamicChart = new DynamicChartComponent();
myDynamicChart.setAnnotation(averageValue);
myDynamicChart.update();我发现ViewChild装饰器产生了这个错误:
Object(...) is not a function我在这里做错了什么?
其他问题的答案提到了ng2-charts-x的使用,但这并没有解决我的问题。
发布于 2020-12-11 02:36:03
我今天遇到了这个问题,并通过打电话解决了这个问题:
this.chart.ngOnChanges({});而不是
this.chart.update()ngOnChanges调用会导致图表更新并显示我以编程方式添加的注释,而在调用update时,它们根本不会显示。希望这能帮助任何在这个问题上遇到困难的人。
https://stackoverflow.com/questions/56218539
复制相似问题