angular2-chartjs / chartjs-plugin-annotation只有一次更新选项

时间:2017-09-21 19:18:56

标签: javascript angular charts highcharts

我使用angualr2-chartjs作为显示图表。我的问题是图表更新只是我动态更改选项的一次。在控制台中我看到一切都很好,但在视野中我看不到变化。我使用了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>

在控制台中我可以看到新的价值线,当下次点击我看不到视图中的变化时,此更新只有一次在视图中。

非常感谢!

1 个答案:

答案 0 :(得分:1)

您必须按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);
}