Renan Ceratto
Renan Ceratto

Reputation: 150

How to add datalabels to chartJS on Primefaces

I'm creating charts with the new ChartJS lib on Primefaces, but I could not find a way to add the value as label on the bar chart or line chart.

Looking on the internet, I've found a JS plugin called chartjs-plugin-datalabels! that does what I need.

How could I use this plugin on my Java Primefaces application?

Upvotes: 2

Views: 4560

Answers (1)

Melloware
Melloware

Reputation: 12019

Try this...

  1. Add the script to your XHTML page:
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  1. In your Java model for your chart set the Extender feature on.
chartModel.setExtender("chartExtender");
  1. In your XHTML add this JavaScript code function to match when you set in #2 Java bean.
function chartExtender() {
   var options = {
      plugins: [ChartDataLabels],
      options: {
         plugins: {
            // Change options for ALL labels of THIS CHART
            datalabels: {
               color: '#36A2EB'
            }
         }
      },
      data: {
         datasets: [{
            // Change options only for labels of THIS DATASET
            datalabels: {
               color: '#FFCE56'
            }
         }]
      }
   };

   //merge all options into the main chart options
   $.extend(true, this.cfg.config, options);
};

This was all based on their configuration guide https://chartjs-plugin-datalabels.netlify.com/guide/getting-started.html#configuration But this should at least get the plugin going.

Upvotes: 9

Related Questions