ng2-charts
ng2-charts copied to clipboard
Cannot get the real chart object
Goal:
I want to access the Chartjs object where I can do stuff like:
this.chart.chart.ctx.drawImage(...);
this.chart.chart.height;
or this.chart.chart.innerRadius.
and so on.
in #776 I learned to use @ViewChild('mycanvas') chart: BaseChartDirective;
However I dont really get access to those mentioned options as this.chart.chart is undefined.
Reproduction: I have adjusted https://stackblitz.com/edit/ng2-charts-doughnut-template :
import { Component, OnInit,ViewChild } from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label } from 'ng2-charts';
import { BaseChartDirective } from 'ng2-charts';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
// Doughnut
public doughnutChartLabels: Label[] = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'];
public doughnutChartData: MultiDataSet = [
[350, 450, 100],
[50, 150, 120],
[250, 130, 70],
];
public doughnutChartType: ChartType = 'doughnut';
@ViewChild('mycanvas') chart: BaseChartDirective; //<------This is important
constructor() { }
ngOnInit() {
console.log(JSON.stringify(this.chart));
}
ngAfterViewInit(): void {
console.log(JSON.stringify(this.chart));
console.log(this.chart.chart); //<-----undefined
}
}
Also the html-canvas tag got the '#mycanvas' element.
My ultimate Goal is to get a picture to be rendered inside a doughnut chart. I got that to work with a plugin (following this: https://stackoverflow.com/a/55727282) however I couldnt find a way to change the picture on runtime. So I thought I will rewrite everything by accessing the chart.js object.
I found that the way how I did the '#mycanvas' was wrong:
wrong:
<canvas baseChart
#mycanvas //<------add: ="base-chart"
style="position: center"
[data]="chartData"
[legend]="false"
[labels]="chartLabels"
[chartType]="doughnutChartType"
[plugins]="doughnutChartPlugins"
></canvas>
correct:
<canvas baseChart
#mycanvas="base-chart" //<------add: ="base-chart"
style="position: center"
[data]="chartData"
[legend]="false"
[labels]="chartLabels"
[chartType]="doughnutChartType"
[plugins]="doughnutChartPlugins"
></canvas>
Aparently the difference is that '#mycanvas' without the base-chart value is only returning the nativeElement, while with the value would map it to the class.