angular2-chartjs/chartjs-plugin-annotation update options only one time

Viewed 2470

I used angualr2-chartjs for display charts. My problem is that chart update is only one time when i change options dynamicly. In console i see that everything is good but in view i cant see changes. i used chartjs-plugin-annotation and i want changes annotation type: "line" value dynamicly when i click button
My config 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)
}

my view:

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

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

in console i can see new value line, and this update only one time in view when click next time i cant see changes in view.

thanks alot!

1 Answers

You have to access the annotation element by id and then change/update it­'s value, like so :

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);
}
Related