[Chartjs]-How to dynamically change the annotation value in Chart.js

0👍

In case someone still lands here by googling: It’s a bug. As a workaround you can remove the ID from your annotation but that might break mouse events. More info here.

0👍

call chart-plugin-annotation updated values through function by passing parameters that you want to change.

0👍

Here is what works for me. I’m using a separate function to set the new value and text label then call the chart.update() method. works fine for me.
see chart.js documentation on updating charts and its options.

options: { // chart.js options object

...

annotation: {
              annotations: [
                {
                  type: 'line',
                  mode: 'horizontal',
                  scaleID: 'y-percent',
                  value: 0,
                  borderColor: 'rgba(238, 68, 226,0.2)',
                  borderWidth: 2,
                  borderDash: [5,5],
                  label: {
                    enabled: true,
                    content: 'Your text label ',
                    position: 'end',
                    drawTime: 'afterDatasetsDraw',
                    backgroundColor: 'rgba(238, 68, 226,0.4)'
                  }
              },
              
          
              ]
            }, // annotation
} // options

setAnnotationValue(val){
      chart.options.annotation.annotations[0].value = val; // set the Value
      chart.options.annotation.annotations[0].label.content += " "+ val + "%"; // append the value to the label (if applicable)
      chart.update(); // and finally update the chart.
    },

Leave a comment