[Chartjs]-Multiple charts on same page not working – ng2-charts

4👍

you should use with the @ViewChildren decorator:

HTML:

<div style="display: block" *ngIf="isDataAvailable1">
<canvas baseChart width="400" height="250"
    [data]="custStateChartData"
    [labels]="custStateChartLabels"
    [chartType]="doughnutChartType"></canvas> 

<div style="display: block" *ngIf="isDataAvailable2">
    <canvas baseChart width="400" height="250"
        [data]="custReleaseChartData"
        [labels]="custReleaseChartLabels"
        [chartType]="doughnutChartType1"></canvas>
</div>

component.ts:

  import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
  import { BaseChartDirective, } from 'ng2-charts';

  export class DashboardComponent implements OnInit{

     ...

     @ViewChildren( BaseChartDirective )
       charts: QueryList<BaseChartDirective>
     ...

the access to the first chart:

    this.charts[0]... 

to update the first chart:

   this.custStateChartData.push(55);
   this.custStateChartLabels.push('abc');  
   this.charts[0].ngOnChanges({});

you can loop it:

this.charts.forEach((c) => {
      c.ngOnChanges({});
  });

Leave a comment