如何通过JavaScript或Angular在PrimeNG饼图内显示数值?
Got it, let's get those values (even negative ones like -50) showing right inside your PrimeNG pie chart slices! Since PrimeNG's <p-chart> is built on top of Chart.js, we can use Chart.js's official plugins and configuration to make this happen easily.
Step 1: Install the Chart.js Data Labels Plugin
First, we need the chartjs-plugin-datalabels plugin—it's the simplest way to add internal labels to chart elements. Install it via npm:
npm install chartjs-plugin-datalabels --save
Step 2: Update Your Component Code
Modify your app.component.ts to register the plugin, set up the chart options for labels, and include negative values in your dataset:
import { Component } from '@angular/core'; import ChartDataLabels from 'chartjs-plugin-datalabels'; import { Chart } from 'chart.js'; export class PieChartDemo { data: any; chartOptions: any; constructor() { // Register the data labels plugin globally Chart.register(ChartDataLabels); this.data = { labels: ['A', 'B', 'C'], datasets: [{ data: [300, -50, 100], // Example with positive and negative values backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"], hoverBackgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"] }] }; this.chartOptions = { plugins: { datalabels: { color: '#ffffff', // White text for contrast against slice colors font: { weight: 'bold', size: 14 }, // Format the value to show as-is (including negatives) formatter: (value: number) => value.toString(), // Position label in the center of each slice anchor: 'center', align: 'center' } } }; } }
Step 3: Update Your Template
Bind the chartOptions to your <p-chart> component in app.component.html:
<div style="display: block"> <p-chart type="pie" [data]="data" [options]="chartOptions"></p-chart> </div>
How It Works
- The
chartjs-plugin-datalabelshandles rendering the labels directly on each pie slice. - The
formatterfunction ensures we display the exact value (positive or negative) without any modifications. - The
anchorandalignsettings make sure the label sits perfectly in the center of each slice for readability.
That's it! Your pie chart will now show all values—including negatives—right inside each corresponding slice.
内容的提问来源于stack exchange,提问作者Sudhin

