Angular 2 ng2-charts doughnut text in the middle?

Ivan Juarez picture Ivan Juarez · Mar 8, 2017 · Viewed 9.9k times · Source

I am using Doughnut chart from ng2-charts (http://valor-software.com/ng2-charts/) in angular 2. I have been searching for an option to put a text in the middle without success. I already searched in ng-chart options as in chart.js (dependency). Do you know another way to achieve this in Angular 2 typescript? or there is something I am missing?

Answer

powerranger picture powerranger · Mar 28, 2017

You can do the following to place text in the center of doughnut chart. It worked for me

HTML:

 <div style="display: block">
  <canvas #mycanvas baseChart 
              [data]="doughnutChartData"
              [labels]="doughnutChartLabels"
              [chartType]="doughnutChartType"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>
</div>

Typescript

import {Component, NgModule, ElementRef, Inject, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ChartsModule, Color} from 'ng2-charts';

export class App{
   @ViewChild('mycanvas')
  canvas:ElementRef; 

 ngOnInit(){
    var ctx = this.canvas.nativeElement.getContext("2d");

    let me = this;
    this.options = {

      circumference: Math.PI,
      rotation :  Math.PI,
      animation:{ onComplete: function() {
         me.doit(ctx);
       }}
    }

      }

     doit(ctx) {
         //   Chart.types.Doughnut.prototype.draw.apply(this, arguments);

            var width = this.canvas.nativeElement.clientWidth,
                height = this.canvas.nativeElement.clientHeight;

            var fontSize = (height / 250).toFixed(2);
            ctx.font = fontSize + "em Verdana";
            ctx.textBaseline = "middle";
            ctx.fillStyle = "blue";

            var text = "Pass Rate 82%",
                textX = Math.round((width - ctx.measureText(text).width) / 2),
                textY = height -10;

            ctx.fillText(text, textX, textY);
            ctx.restore();
        }
}
}