To begin, execute the following npm commands:
npm install ng2-charts --save
npm install chart.js --save
Remember: It is crucial to embed Chart.js in your application by including it in your index.html file.
<script src="node_modules/chart.js/src/chart.js"></script>
Next, import ChartsModule in App.module.ts
import { ChartsModule } from 'ng2-charts';
imports: [ChartsModule]
For your Component.html file:
<div style="display: block">
<canvas baseChart
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
In your Component.ts file:
public pieChartLabels: string[] = ['Male', 'Female'];
public pieChartData: number[] = [51, 30];
public pieChartType: any = 'pie';
// events
public chartClicked(e: any): void {
console.log(e);
}
public chartHovered(e: any): void {
console.log(e);
}
This code functions as expected and should work smoothly for you.