gpt4 book ai didi

javascript - angular2-chartjs/chartjs-plugin-annotation 更新选项仅一次

转载 作者:行者123 更新时间:2023-11-30 21:08:41 27 4
gpt4 key购买 nike

我使用 angualr2-chartjs 来显示图表。我的问题是当我动态更改选项时图表更新只有一次。在控制台中,我看到一切都很好,但在 View 中我看不到变化。我使用了 chartjs-plugin-annotation 并且我希望在单击按钮时动态更改注释类型:“line”值
我的配置 app.component.ts:

import { Component,ViewChild,ChangeDetectorRef } from '@angular/core';
import { ChartComponent } from 'angular2-chartjs';
import 'chartjs-plugin-datalabels';
import 'chartjs-plugin-annotation';
.
.
.
public barChartOptions:any = {
scales: {
xAxes: [{stacked: true,ticks: {mirror: true}}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true,
}
}]
},
annotation: {
events: ["click"],
annotations: [{
drawTime: "afterDatasetsDraw",
id: "hline",
type: "line",
mode: "horizontal",
scaleID: "y-axis-0",
value: 30,
borderColor: "black",
borderWidth: 1,
label: {
backgroundColor: "red",
content: "Target line",
enabled: true
},
onClick: function(e) {
// The annotation is is bound to the `this` variable
console.log("Annotation", e.type, this);
}
}]},
responsive: true,
showTooltips: false,

}


public barChartType:string = 'bar';

public barChartData = {
labels: ['val1', 'val2'],
datasets: [
{
label: "var1",
backgroundColor: "#F29220",
borderColor: "#F29220",
data: [40,20],
datalabels: {
align: 'center',
anchor: 'center',
color: '#fff'
}
},
{
label: "var2",
backgroundColor: "#4365B0",
borderColor: "#4365B0",
data: [60,80],
datalabels: {
align: 'center',
anchor: 'center',
color: '#fff'
}
}],

};
//change value line
public addNewBarValue():void {
this.chartComponent.chart.annotation.options.annotations[0].value += 10;
this.chartComponent.chart.update();
console.log(this.chartComponent.chart.annotation.options.annotations[0].value)
}

我的看法:

 <div><chart [type]="barChartType" [data]="barChartData" [options]="barChartOptions"></chart>

<button (click)="addNewBarValue()">Update</button></div>

在控制台中我可以看到新的值线,并且此更新仅在 View 中显示一次,下次单击时我看不到 View 中的变化。

非常感谢!

最佳答案

您必须通过 id 访问注释元素,然后更改/更新它值,如下所示:

public addNewBarValue(): void {
this.chartComponent.chart.annotation.elements['hline'].options.value += 10;
this.chartComponent.chart.update();
console.log(this.chartComponent.chart.annotation.elements['hline'].options.value);
}

关于javascript - angular2-chartjs/chartjs-plugin-annotation 更新选项仅一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46351646/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com