Chartjs-How to display the values inside the pie chart of PrimeNG (chart) using JavaScript or Angular

4👍

It’s late, and i think you already found an answer, but for future people this can be achieved as follows:

  1. Install plugin: npm install chartjs-plugin-datalabels –save
  2. It would be registred globaly, and we need to unregister it, in order to include only for certain charts; place it, for example, in init method of root component

     import * as Chart from 'chart.js';
     import ChartDataLabels from 'chartjs-plugin-datalabels';
     ...
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    
    export class AppComponent implements OnInit {
       chartJs = Chart;
       chartLabelPlugin = ChartDataLabels;
    
       constructor() {
       }
    
       ngOnInit(): void {
         this.chartJs.plugins.unregister(this.chartLabelPlugin);
      }
    }
    
  3. Add plugin for certain chart

    import ChartDataLabels from 'chartjs-plugin-datalabels';
    ...
    
    plugin = ChartDataLabels; 
    options = {
      plugins: {
       datalabels: {
         /* show value in percents */
         formatter: (value, ctx) => {
           let sum = 0;
           const dataArr = ctx.chart.data.datasets[0].data;
           dataArr.map(data => {
                 sum += data;
           });
           const percentage = (value * 100 / sum); 
           return percentage !== 0 ? percentage.toFixed(2) + '%' : '';
         },
         color: '#fff',
       }
      }
    }
    
    
    
    <-- html -->
    
     <p-chart [options]="options" 
              [data]="dataset" 
              [plugins]="plugin" 
              type="pie">
     </p-chart>
    
    <-- html -->
    

1👍

This answer is correct but in app.component.ts you must import chartjs-plugin-datalabels

like this:
import * as ChartDataLabels from ‘chartjs-plugin-datalabels’;

not like this:
import ChartDataLabels from ‘chartjs-plugin-datalabels’;

Thank u so much Alexey.S!

Leave a comment