Chartjs-Angular Chart.JS Only One Canvas Rendering

2👍

Problem was with your canvas id, you should pass dynamic ids to your chart.

For example:

You have to pass dynamic ids from your component to the canvas.

and you have instantiate your Chart in ngAfterViewInit ie. after View gets initialized.

Your chart template should be like this:

<div class="chart-container">    
    <canvas [id]="chartId" >{{ barChart }}</canvas>    
  </div>
  barchart test

and in your component it should be like this:

export class BarchartComponent implements OnInit {
  @Input() chartId:string;
  barChart = [];
  constructor(
  ) { }

  ngOnInit(): void {
    setTimeout(() => {
      this.barChart = new Chart(this.chartId, {
      type: 'bar',
      data: {
        backgroundColor: "#000000",
        labels: ['4H', '4L', 'Close'],
        datasets: [{
          label: '# of Inc.',
          data: [2,3,1],
          borderColor: '#000000',
          backgroundColor: "#000000",
        }]
      },
      options: {
        maintainAspectRatio: false,
        legend: {
          display: false
        },
        scales: {
          xAxes: [{
            display: true,
            gridLines: {
              // display: false,
              drawOnChartArea: false,
              zeroLineColor: '#000000',
              color: '#000000',
              fontStyle: "bold",
            },
            ticks: {
              fontColor: '#000000',
              fontFamily: 'Lato',
              fontStyle: "bold",
              precision:0
            },
          }],
          yAxes: [{
            display: true,
            gridLines: {
              drawOnChartArea: false,
              zeroLineColor: '#000000',
              color: '#000000',
              fontStyle: "bold",
            },
            ticks: {
              fontColor: '#000000',
              fontFamily: 'Lato',
              fontStyle: "bold",
              precision:0
            },
          }],
        }
      }
    }, 100);
    })
  
  }

}

Here is the working demo for the same.
demo

Leave a comment