npm install chart.js@^3.0.0
hr-chart.page.html:
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title></ion-title>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true" >
<ion-card>
<ion-card-header>休假图表</ion-card-header>
<ion-card-content>
<!-- 由于是通过 canvas 绘制出图表,所以需要有一个 canvas 标签,并且通过 #pieCanvas 来获取dom -->
<canvas #barCanvas></canvas>
</ion-card-content>
</ion-card>
</ion-content>
hr-chart.page.ts
import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { ViewChild } from '@angular/core';
import { ElementRef } from '@angular/core';
import { AfterViewInit } from '@angular/core';
import { registerables } from 'chart.js';
@Component({
selector: 'app-hr-chart',
templateUrl: './hr-chart.page.html',
styleUrls: ['./hr-chart.page.scss']
})
export class HrChartPage implements AfterViewInit {
@ViewChild('barCanvas', { static: true }) barCanvas!: ElementRef;
barChart: any;
ngAfterViewInit() {
Chart.register(...registerables); // 注册 Chart.js 的所有模块
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
type: 'linear', // 修改为正确的线性类型
beginAtZero: true
}
}
}
});
}
}