kintela
kintela

Reputation: 1323

problems with ChartJS refresh in angular component

In my project: https://stackblitz.com/edit/planificador?file=src/app/planificador/components/subcontrataciones/subcontrataciones.component.ts

I have in a mat-expansion-panel a component with a ChartJS canvas but the problem I have is that once configured, the data is assigned to the chart when I open the extension panel, these are not shown until I stretch the screen.

That is to say, from the start I see this

empty

and after stretching and shrinking the screen the data appears

data

In grafica.component.ts I have this

ngAfterViewInit() {
this.mostrarGraficoMezclado();

}

 mostrarGraficoMezclado() {
this.canvas = this.mychart.nativeElement;
this.ctx = this.canvas.getContext('2d');

var options = {
  scales: {
    xAxes: [
      {
        barPercentage: 0.5,
        barThickness: 6,
        maxBarThickness: 8,
        minBarLength: 2,
        gridLines: {
          offsetGridLines: true
        }
      }
    ]
  }
};

var mixedChart = new Chart(this.ctx, {
  type: "bar",
  data: {
    datasets: [
      {
        label: "Contratado Previsto",
        data: this.contratoPrevistoAcumulado,
        borderColor: "blue",
        type: "line"
      },
      {
        label: "Gastado Realizado",
        data: this.gastadoRealizadoAculumado,
        borderColor: "green",
        type: "line"
      },
      {
        label: "Certificado Realizado",
        data: this.certificadoRealizadoAculumado,
        borderColor: "red",
        type: "line"
      },
      {
        label: "Gasto Previsto Total",
        data: this.gastadoPrevisto,
        backgroundColor: "orange"
      },
      {
        label: "Certificado Previsto",
        data: this.certificadoPrevisto,
        backgroundColor: "maroon"
      },
      {
        label: "Historico de Previsiones",
        data: this.historicoPrevisionesN,
        backgroundColor: "black"

      }
    ],
    labels: this.etiquetasEjeX
  },
  options: options
});

}

Any idea, please?

Upvotes: 0

Views: 546

Answers (1)

uminder
uminder

Reputation: 26170

The problem can be solved if you don't invoke mostrarGraficoMezclado() inside ngAfterViewInit() but rather at the end of getDatosGlobalesGrafica(), just after getDatosGrafica().

This makes sure, the chart gets created only once its data is available.

getDatosGlobalesGrafica(proyectoId: string, acumular: boolean) {
  ...
  zip(...)
     .pipe(...)
     .subscribe(
        ...
        this.getDatosGrafica();
        this.mostrarGraficoMezclado();
     );
  );  
}

Upvotes: 2

Related Questions