[Chartjs]-Angular 5, Chart.js displaying multiple charts, one on each tab

1๐Ÿ‘

Tab contents of mat-tabs can be lazy loaded by declaring the body in a ng-template with the matTabContent attribute. Additionally each chart should has its own canvas/context (property canvasID):

 <mat-tab *ngFor="let store of stores" label="{{store.store_code}}">
   <ng-template matTabContent>
     <app-store-dash-board [store_code]="store.store_code" [canvasId]="store.canvasId"></app-store-dash-board>
   </ng-template>
 </mat-tab>

-1๐Ÿ‘

U must create the canvas with Id and get the context when the component is loading.

import { Chart } from 'chart.js';

// Variables
  canvas: any;
  ctx: any;
// Chart de Chart.Js
 chart: any;

  ngAfterViewInit() {
    this.canvas = document.getElementById('my_canvas');
    this.ctx = this.canvas.getContext('2d');

    this.createChart();
  }

  private createChart() {
     this.chart = new Chart(this.ctx, {
       type: 'bar',
       data:,
       options,
     });
 }

Try to use ngAfterViewInit so the component dont try to get the context before the DOM is loaded.

Leave a comment