How to Create a Custom Chart Component in Angular

  How to Create a Custom Chart Component in Angular


Overview: In this blog post, we'll explore how to create a custom chart component in Angular using the Chart.js library. We'll cover the basics of setting up a new Angular app, installing and configuring Chart.js, and creating a reusable chart component that can be used in any Angular app.


Code Snippet:


typescript


import { Component, Input, OnInit } from '@angular/core';

import * as Chart from 'chart.js';


@Component({

  selector: 'app-chart',

  template: `

    <canvas #canvas></canvas>

  `,

})

export class ChartComponent implements OnInit {

  @Input() data: number[];

  @Input() labels: string[];


  private chart: Chart;


  constructor() {}


  ngOnInit(): void {

kotlin

Copy code

this.createChart();

}


private createChart(): void {

const canvas = document.querySelector('canvas');

const ctx = canvas.getContext('2d');


yaml

Copy code

this.chart = new Chart(ctx, {

  type: 'bar',

  data: {

    labels: this.labels,

    datasets: [

      {

        data: this.data,

        backgroundColor: 'rgba(54, 162, 235, 0.2)',

        borderColor: 'rgba(54, 162, 235, 1)',

        borderWidth: 1,

      },

    ],

  },

  options: {

    responsive: true,

    scales: {

      yAxes: [

        {

          ticks: {

            beginAtZero: true,

          },

        },

      ],

    },

  },

});

}

}



No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...