i try to make pie graph on angular and i use Chartjs and i get error when i try run my project

62 Views Asked by At

code share below:

html

<div>
  <canvas baseChart
          [data]="pieChartData"
          [colors]="colors"
          [labels]="pieChartLabels"
          [chartType]="pieChartType"
        >
  </canvas>
</div>

component.ts

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

@Component({
  selector: 'app-pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrl: './pie-chart.component.css'
})
export class PieChartComponent implements OnInit {

  pieChartData: number[] = [350,450,120];
  pieChartLabels: string[] = ['xyz','Logistics','Main st Bakery','Acme hosting'];
  colors: any[] = [
    {
      backgroundColor: ['#26547c','#ff6b6b','#ffd166']
    }
  ];
  pieChartType = 'pie'

  constructor(){}

  ngOnInit(){

  }
}

i want make pie graph

1

There are 1 best solutions below

0
Naren Murali On

After going through the demo pie chart Below is a working example of pie chart generated through ng2-charts package. The following changes were made!

  1. chartType in HTML needs to be type instead.
  2. backgroundColor need to be set inside the datasets array, instead of colors attribute in the html
  3. pieChartData needs to be restructured to contain the datasets within it

code

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { NgChartsModule } from 'ng2-charts';
import { ChartData, ChartType } from 'chart.js';
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [NgChartsModule],
  template: `
    <div>
      <canvas baseChart
              [data]="pieChartDataFinal"
              [labels]="pieChartLabels"
              [type]="pieChartType"
            >
      </canvas>
    </div>
  `,
})
export class App {
  pieChartLabels: string[] = [
    'xyz',
    'Logistics',
    'Main st Bakery',
    'Acme hosting',
  ];
  colors: any[] = [{}];
  public pieChartType: ChartType = 'pie';
  pieChartDataFinal: ChartData<'pie', number[], string | string[]> = {
    datasets: [
      {
        data: [350, 450, 120],
        backgroundColor: ['#26547c', '#ff6b6b', '#ffd166'],
      },
    ],
  };

  constructor() {}

  ngOnInit() {}
}

bootstrapApplication(App);

stackblitz