Home > Blockchain >  How to load NG2Charts when all data is ready
How to load NG2Charts when all data is ready

Time:06-16

I am working on an Angular project, where I want to populate some charts with data that I recieve from Firebase. Since I have to do an async function, the data comes AFTER the chart is loaded, so it is displayinh nothing.

My code is the following:

detail.component.html

<div >
  <div >
    <div >
      <div >
        <span >Employee detail</span>
      </div>
      <div>
        <div>
          <div style="display: block">
            <canvas baseChart
              [data]="doughnutChartData"
      
              [type]="doughnutChartType">
            </canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

detail.component.ts

import class DetailComponent implements OnInit {
  empHoursLearning!: number;
  empHProject1!: number;
  empHProject2!: number;

  public doughnutChartLabels: string[] = [
    'Hours learning',
    'Hours Project 1',
    'Hours Project 2'
  ];
  public doughnutChartData: ChartData<'doughnut'> = {
    labels: this.doughnutChartLabels,
    datasets: [
      {
        data: [this.empHoursLearning, this.empHProject1, this.empHProject2],
        backgroundColor: ['#7DFF93', '#36A2EB', '#FFCE56'],
        hoverBackgroundColor: '#E6E6E6',
        hoverBorderColor: '#E6E6E6',
      },
    ],
  };
  public doughnutChartType: ChartType = 'doughnut';

  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;

  ngOnInit(): void {
    this.getEmpleados();   
  }

  async getEmployee() {
    await this._employeeService.getEmployee().then((employees) => {
      this.empHoursLearning= employees!['hl'];
      this.empHProject1= empleados!['p1'];
      this.empHProject2= empleados!['p2'];
    });
  }
}

My question is how to make the chart to render once all the data is received.

CodePudding user response:

As Mentioned in the similar thread:

Use a loading flag combined with *ngIf to wait for the data from the service to be loaded before initializing the chart.

I.e

<canvas *ngIf="loaded" baseChart 
  [data]="doughnutChartData" 
  [type]="doughnutChartType"> 
</canvas>
  • Related