0

I wish to draw the percentages on the pie pieces of a Chart.js pie chart, in my Ionic 4 / Angular application.

My Chart.js version is 2.8.0

I have the following code I found here, where I can see it works. But when I add it, my formatter() is just not called (I have added a breakpoint and it is just not called)

        public ngOnInit() : void {
        this.data = {
          datasets: [{
            data: [10, 20, 30, 50],
            backgroundColor: [
              'green',
              'rgba(54, 162, 235, 0.2)',
              'rgba(255, 206, 86, 0.2)',
              'rgba(75, 192, 192, 0.2)',
              'rgba(153, 102, 255, 0.2)',
              'rgba(255, 159, 64, 0.2)'
            ],
          }],

          labels: [
            'Red',
            'Yellow',
            'Blue',
            'another'
          ]
        };

        let options = {
          responsive: true,
          maintainAspectRatio: false,
          legend: {
            position: 'bottom',
            boxWidth:10
          },
          tooltips: {
            enabled: false
          },
          plugins: {
            datalabels: {
              formatter: (value, ctx) => { // this is never called
                return 'hello';
                let sum = 0;
                let dataArr = ctx.chart.data.datasets[0].data;
                dataArr.map(data => {
                  sum += data;
                });
                let percentage = (value * 100 / sum).toFixed(2) + "%";
                return percentage;


              },
              color: 'black',
            }
          }
        };
        this.chart = new Chart(this.chartRef.nativeElement, { 
          type: 'pie',
          data: this.data,
          options: options
        });
      }

Why is this working not for me? Apart from that, most other things on the charts seem to work fine.

halfer
  • 19,824
  • 17
  • 99
  • 186
peterc
  • 6,921
  • 9
  • 65
  • 131
  • did you add the plugin to the page? --> `` – WhiteHat Apr 09 '19 at 19:32
  • @WhiteHat - thanks for that. No I did not realise there was another package to install. Do you know how to use this within Angular via an `npm package`? I Have seen others say just do a `import 'chartjs-plugin-datalabels';` but this gives me `[ng] ERROR in node_modules/chartjs-plugin-datalabels/types/index.d.ts(5,16): error TS2665: Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'D:/dev/ionic/chartjstest/node_modules/chart.js/dist/Chart.js', which cannot be augmented.` – peterc Apr 10 '19 at 00:23

0 Answers0