Chartjs-Angular 7 how to draw dynamic number of charts

1๐Ÿ‘

โœ…

I think this answer is help for creating multiple dynamic chart.

Parent:

HTML:

<div [hidden]="!charts" class="divchart">
  <div *ngFor="let chart of charts; let i = index">
    <app-child [chart]="chart" [id]="i"></app-child>
  </div>
</div>

TS:

import { Component } from '@angular/core';
import { ListService } from './list.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public charts = [];
  constructor(private listsrv: ListService) { }
  ngOnInit() { 
    this.charts.push('canvas0');

    this.listsrv.getPosts()
    .subscribe(
      result => {         
        for(var key in result){          
          if(result[key].id < 3){
            this.charts.push('canvas'+ result[key].id);
          }
        } 
      },
      error => {console.log(' error',error)},
      () => {
        console.log('service call completed',this.charts)    
      }
    )     
  }  
}

child:

HTML:

<div *ngIf="chart">
  <canvas id="{{chart}}" width="400" height="400">{{chart}}</canvas>
</div>

TS:

import { Component, OnInit, Input } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() chart: any;
  @Input() id: any;
  constructor() { }

  ngOnInit() {
  }
  ngAfterViewInit() {
      this.addchart(this.chart);
  }

   addchart(chartid){
    console.log(chartid);
    console.log(document.getElementById(chartid));
    var canvas = <HTMLCanvasElement> document.getElementById(chartid);
    var ctx = canvas.getContext("2d");
    var mychart = new Chart(ctx, {
      type: 'line',
      data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Cyan'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19, 3, 5, 2, 3, 7],
              backgroundColor: 'lightgreen',
              borderColor: 'blue',
              borderWidth: 1
          }]
      },
      options: {
          legend: {
            display: false
        },
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
    });
  }

}

You can also check in provided a link: https://stackblitz.com/edit/angular-dinauz

Leave a comment