首先,确保你已经正确安装了PrimeNG和Chart.js依赖。
在你的组件中引入PrimeNG的PieChartModule,并将其添加到你的app中的imports数组中。
import { PieChartModule } from 'primeng/piechart';
@NgModule({
imports: [
...,
PieChartModule
],
...
})
export class AppModule { }
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-chart',
template: `
`
})
export class ChartComponent implements OnInit {
data: any;
options: any;
ngOnInit() {
this.data = {
labels: ['Label 1', 'Label 2', 'Label 3'],
datasets: [
{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
this.options = {
title: {
display: true,
text: 'My Pie Chart'
}
};
}
}
import { Component, OnInit, NgZone } from '@angular/core';
@Component({
selector: 'app-chart',
template: `
`
})
export class ChartComponent implements OnInit {
data: any;
options: any;
constructor(private zone: NgZone) {}
ngOnInit() {
// Create data and options objects ...
// Ensure chart config has been re-drawn by Angular after page load
this.zone.runOutsideAngular(() => {
setTimeout(() => {
window.dispatchEvent(new Event('resize'));
}, 0);
});
}
}
这样,在你的组件模板中,饼图应该会正确地显示出来了。