Hello guys
I'm tried to use the plugin in angular but i can't use the plugin,
i imported this plugin and installed the NPM package module but the dependencie dosen't works
One solution for this problem .
PD: Before the all i work from mexican companie for this mi comentaries are wrote in spanish
import * from 'chartjs-plugin-datalabels';
this is the code in html
`
<canvas #mycanvas baseChart [data]="doughnutChartData" [labels]="doughnutChartLabels" [options]="options"
[chartType]="doughnutChartType" [colors]="color">
`
this is the code in TypeScript
`import { Component, OnInit, Input, QueryList, ViewChildren, ViewChild, ChangeDetectorRef, OnChanges } from '@angular/core';
import { DashboardService } from '../../../../../core/services/dashboard.service';
import { BaseChartDirective, Color } from 'ng2-charts';
import { Chart } from 'chart.js';
import { isString } from '@ng-bootstrap/ng-bootstrap/util/util';
@component({
selector: 'm-pichart-warehouse',
templateUrl: './pichart-warehouse.component.html',
styleUrls: ['./pichart-warehouse.component.scss']
})
export class PichartWarehouseComponent implements OnInit,OnChanges {
//El tipo de grafica que sera 0 = Secos 1 = Frios 2 = Congelados
@input() typeLoad: number;
@ViewChildren(BaseChartDirective) charts: QueryList;
@ViewChild(BaseChartDirective) private _chart;
//Propiedad de donde obtiene la grafica el nombre
public doughnutChartLabels: string[] = ['Vacio'];
//Propiedad donde la grafica obtiene sus datos
public doughnutChartData: any = [0];
//El tipo de grafica que vendra
public doughnutChartType: string = 'doughnut';
//El color de la grafica por defecto si no contiene nada
public color: Color[] = [
{ backgroundColor: ['#578EBE', '#F36A5A', '#F2784B', '#E08283', '#1BBC9B', '#8E44AD', ' #F4D03F', '#E5E5E5'] }
];
//Las opciones que tendra personalizadas la grafica
public options: any = {
showActualPercentages: true,
legend: {position: 'left'},
// Aqui se agrega el label central
elements: {
center: {
text: '' + this.doughnutChartData.reduce((a, b) => a + b, 0) + '%',
color: '#FFFFF',
// fontStyle: 'Arial',
sidePadding: 20
}
},
//Aqui genera el label que se muestra en el mouse hover
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
let allData = data.datasets[tooltipItem.datasetIndex].data;
let tooltipLabel = data.labels[tooltipItem.index];
let tooltipData = allData[tooltipItem.index];
let total = 0;
for (let i in allData) {
total += allData[i];
}
let tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
}
}
}
}
constructor(
private cdr: ChangeDetectorRef,
private Dashboardservice: DashboardService,
) { }
ngOnInit() {
//Este plugin gemera el label del centro
Chart.pluginService.register({
beforeDraw: function (chart) {
if (chart.config.options.elements.center) {
var ctx = chart.chart.ctx;
var centerConfig = chart.config.options.elements.center;
// var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
ctx.font = "30px ";
// + fontStyle;
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
var fontSizeToUse = Math.min(newFontSize, elementHeight);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px ";
// + fontStyle;
ctx.fillStyle = color;
ctx.fillText(txt, centerX, centerY);
}
}
});
}
ngOnChanges(changues) {
this.loadWharehousebyLocation();
}
/**
- Obitiene los valores del back y los asigna a la grafica que muestra en pantalla
- @param Time Este parametro dice cual es el rango de fecha se obtendran los datos
*/
loadWharehousebyLocation(): void {
this.Dashboardservice.findWarehousebyLocation(this.typeLoad).subscribe(res => {
if (res.data.Ware.length == 0) {
this.chargeDefaultToChart();
} else {
this.chargeDataToChart(res.data.Ware);
}
});
}
/**
- Esta funcion carga al char todos los valores del obtenidos
- @param data.name obtendra los nombres de los clientes
- @param data.id obtiene la cantidad de registros
*/
chargeDataToChart(data: any[]): void {
Object.keys(data).map(i => data[i])
let client_names: string[] = [], io_values: any[] = [];
data.forEach(item => {
client_names.push(item.name);
if(isString(item.count)){
io_values.push( Number(item.count) );
}else{
io_values.push(item.count);
}
});
this.doughnutChartLabels.length = 0;
this.doughnutChartLabels.push(...client_names);
this.doughnutChartData = [];
this.doughnutChartData = io_values;
this.cdr.detectChanges();
this.updateChart();
}
/**
- Realiza las funciones necesarias para dar update a las graficas
*/
updateChart(): void {
this.options.elements.center.text = "";
let text =this.generatePercentage(this.doughnutChartData);
console.log(text);
this.options.elements.center.text = text;
this.forceChartRefresh();
}
/**
- Hace update forsado a los charts
*/
forceChartRefresh(): void {
setTimeout(() => {
this._chart.refresh();
}, 10);
this.charts.forEach((child) => {
child.chart.update();
});
}
/**
- Carga todos los valores por defecto de la grafica
*/
chargeDefaultToChart(): void {
this.doughnutChartLabels = ['Vacio'];
this.doughnutChartData = [0];
this.cdr.detectChanges();
this.options.elements.center.text = "";
this.options.elements.center.text = "0%";
this.forceChartRefresh();
}
/**
- Obtiene un array para calcular el porcentage de uso
- @param Values obtiene un array de valrores numericos EJ [2,3,46,7]
*/
generatePercentage(Values: number[] ): string{
let total_used = 0;
for(let i =0;i < Values.length-1;i++ ){
total_used += Values[i];
}
let percentage: number = ((total_used / Values.reduce((a, b) => a + b, 0)) * 100);
return ""+percentage.toFixed()+"%"
}
}`
If can help me with that i appreciated to much that because the plugin this plugin are good