[Chartjs]-Using two JSON objects to make Chart.JS Bar Chart Dynamic in Typescript / Angular

1πŸ‘

βœ…

The chart.js documentation is probably the best resource in terms of structuring the data for input. From what I understand of your question, you want to toggle between bar graphs in the same chart right? I put together a little stackblitz example of using chart.js in angular to do this. Basically, the chart configuration object defines what gets drawn. This needs to be swapped depending on the data you want to chart and re-rendered. Hope this is helpful / relevant. Apologies if I misunderstood your question.

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


const dataset1 = {
                  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                  datasets: [{
                      label: '# of Votes',
                      data: [12, 19, 3, 5, 2, 3],
                  }]
              };

const dataset2 = {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        label: '# of People',
        data: [3, 5, 2, 12, 19, 3],
    }]
};

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
  chart: Chart;

  @ViewChild('graph', { static: true }) 
  graph: ElementRef;

  ctx: CanvasRenderingContext2D;

  currentDataSet = dataset1;
  
  constructor() {}

  ngOnInit() {
    this.ctx = (<HTMLCanvasElement>this.graph.nativeElement).getContext(
      '2d',
    );

    this.renderChart();
  }

  renderChart(){
    this.chart = new Chart(this.ctx, this.chartConfig);
  }

  pick(dataSet){
    this.currentDataSet = dataSet === 1 ? dataset1 : dataset2;
    this.renderChart();
  }

  get chartConfig(): Chart.ChartConfiguration {
    return  {
              type: 'bar',
              data: this.currentDataSet,
              options: {
                  scales: {
                      yAxes: [{
                          ticks: {
                              beginAtZero: true
                          }
                      }]
                  }
              }
          }
  }
}

2πŸ‘

if posible, I think would be better if you used a version of chart that is totally compatible with your version of Angular, like:

But if you realy need to use this version, you could create a array with both values and iterate this array to create your values:

let labels = [{label: "A"}, {label: "B"}, {label: "C"}, {label: "D"}, {label: "E"}];
let values = [{value: 1}, {value: 2}, {value: 3}, {value: 4}, {value: 5}];
let finalArray = [];
labels.forEach((currentLabel, index) => {
    finalArray.push({ label: currentLabel.label, value: values[index].value});
});
/* finalArray will be: 
[
   {label: "A", value: 1}
   {label: "B", value: 2}
   {label: "C", value: 3}
   {label: "D", value: 4}
   {label: "E", value: 5}
];

*/

Leave a comment