emn178 / angular2-chartjs

Chart.js component for Angular2
MIT License
95 stars 21 forks source link

How do I use pluginRegister with angular2-chartjs? #39

Closed DanaEpp closed 6 years ago

DanaEpp commented 6 years ago

First off, let me start by saying thank you for an awesome module for Angular. Wrapping chart.js like this is awesome. Thank you!

Now onto business. I am trying to override the drawing in Chart.js according to some comments found here to add values in the middle of a doughnut chart.

So In my html for my component I have something like this:

<chart type="doughnut" [data]="my_data" [options]="my_options" #my_chart></chart>

In my TypeScript, I have this for imports:

import { Component, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { ChartModule, ChartComponent } from 'angular2-chartjs';

I setup a var as such:

@ViewChild('my_chart') my_chart: ChartComponent;

In ngAfterViewInit, I have something like this:

ngAfterViewInit() {

    this.my_chart.chart.pluginService.register({
      beforeDraw: function(chart) {
        var width = chart.chart.width,
            height = chart.chart.height,
            ctx = chart.chart.ctx;

        ctx.restore();
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";

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

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

    this.my_chart.chart.update();
  }

However, the property of 'register' is always undefined. I thought I had to wait until after viewInit to get a proper handle to the chart... but it seems the register isn't there.

What is the right way to do this? What am I missing?

emn178 commented 6 years ago

Find a place that it should run only once. eg app.moudle. and then

import 'chart.js'
declare var Chart;
Chart.pluginService.register(...)
DanaEpp commented 6 years ago

How do I feed that into ChartModule for use later though? Or are you saying that it will honor that somehow?

Are you saying to create a constructor in AppModule, register the custom drawing there and ChartModule will pick that up later?

DanaEpp commented 6 years ago

Anyone else have any feedback for this?

DanaEpp commented 6 years ago

Thanks for this emn178. I was able to get this working. Much appreciated!