You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中基于ng2-smart-table筛选数据生成Chart.js柱状图统计页求助

实现方案:Angular 筛选健康数据并转为 Chart.js 柱状图

1. 安装必要依赖

先确保项目安装所需依赖包:

npm install chart.js ng2-charts @angular/material @angular/cdk
# 若无需Material组件可跳过相关包,改用原生日期选择器

2. 模块导入配置

在统计页面所属模块(如StatsModule)中导入核心模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { NgChartsModule } from 'ng2-charts';
import { ReactiveFormsModule } from '@angular/forms';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatNativeDateModule } from '@angular/material/core';

import { StatsComponent } from './stats.component';

@NgModule({
  declarations: [StatsComponent],
  imports: [
    CommonModule,
    Ng2SmartTableModule,
    NgChartsModule,
    ReactiveFormsModule,
    MatDatepickerModule,
    MatInputModule,
    MatSelectModule,
    MatNativeDateModule
  ]
})
export class StatsModule { }

3. 组件模板实现

在stats.component.html中构建筛选栏、表格与图表区域:

<!-- 筛选操作区 -->
<div class="filter-bar">
  <mat-form-field>
    <mat-label>选择地点</mat-label>
    <mat-select [(value)]="selectedLocation">
      <mat-option *ngFor="let loc of locations" [value]="loc">{{loc}}</mat-option>
    </mat-select>
  </mat-form-field>

  <mat-form-field>
    <mat-label>日期范围</mat-label>
    <input matInput [matDatepicker]="picker" [(ngModel)]="dateRange" placeholder="选择开始-结束日期">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker startView="multi-year" [rangeMode]="true"></mat-datepicker>
  </mat-form-field>

  <button (click)="applyFilter()">应用筛选</button>
</div>

<!-- 筛选后的数据表格 -->
<ng2-smart-table [settings]="tableSettings" [source]="filteredData"></ng2-smart-table>

<!-- Chart.js 柱状图容器 -->
<div class="chart-container">
  <canvas baseChart
          [datasets]="barChartData"
          [labels]="barChartLabels"
          [options]="barChartOptions"
          [legend]="barChartLegend"
          [chartType]="barChartType">
  </canvas>
</div>

4. 组件逻辑实现

在stats.component.ts中处理筛选、数据转换与图表更新:

import { Component, OnInit } from '@angular/core';
import { ChartConfiguration, ChartType } from 'chart.js';
import { DateRange } from '@angular/material/datepicker';

// 定义健康数据结构(匹配你的实际数据字段)
interface HealthData {
  id: number;
  patientName: string;
  location: string;
  testDate: Date;
  bloodPressure: number;
  bloodSugar: number;
}

@Component({
  selector: 'app-stats',
  templateUrl: './stats.component.html',
  styleUrls: ['./stats.component.css']
})
export class StatsComponent implements OnInit {
  // 模拟原始数据源(实际从API/ng2-smart-table原始数据获取)
  originalData: HealthData[] = [
    { id: 1, patientName: '张三', location: '北京', testDate: new Date('2024-01-05'), bloodPressure: 120, bloodSugar: 5.6 },
    { id: 2, patientName: '李四', location: '上海', testDate: new Date('2024-01-06'), bloodPressure: 130, bloodSugar: 6.1 },
    { id: 3, patientName: '王五', location: '北京', testDate: new Date('2024-01-07'), bloodPressure: 115, bloodSugar: 5.8 }
  ];

  filteredData: HealthData[] = [];
  locations: string[] = ['北京', '上海', '广州', '深圳'];
  selectedLocation: string = '';
  dateRange: DateRange<Date> | undefined;

  // 图表基础配置
  barChartOptions: ChartConfiguration['options'] = {
    responsive: true,
    scales: {
      y: { beginAtZero: true, title: { display: true, text: '检测数值' } },
      x: { title: { display: true, text: '患者姓名' } }
    }
  };
  barChartLabels: string[] = [];
  barChartType: ChartType = 'bar';
  barChartLegend = true;
  barChartData: ChartConfiguration['data']['datasets'] = [];

  // ng2-smart-table 列配置
  tableSettings = {
    columns: {
      id: { title: 'ID' },
      patientName: { title: '患者姓名' },
      location: { title: '检测地点' },
      testDate: { title: '检测日期', valuePrepareFunction: (date: Date) => new Date(date).toLocaleDateString() },
      bloodPressure: { title: '血压' },
      bloodSugar: { title: '血糖' }
    }
  };

  ngOnInit(): void {
    // 初始化加载全部数据
    this.filteredData = [...this.originalData];
    this.updateChart();
  }

  applyFilter(): void {
    // 执行数据筛选
    this.filteredData = this.originalData.filter(item => {
      // 地点匹配逻辑
      const locationMatch = !this.selectedLocation || item.location === this.selectedLocation;
      // 日期范围匹配逻辑
      let dateMatch = true;
      if (this.dateRange?.start && this.dateRange?.end) {
        const itemDate = new Date(item.testDate);
        dateMatch = itemDate >= this.dateRange.start && itemDate <= this.dateRange.end;
      }
      return locationMatch && dateMatch;
    });
    // 同步更新图表
    this.updateChart();
  }

  updateChart(): void {
    // 将表格数据转换为Chart.js所需格式
    this.barChartLabels = this.filteredData.map(item => item.patientName);
    // 构建血压、血糖数据集
    this.barChartData = [
      {
        data: this.filteredData.map(item => item.bloodPressure),
        label: '血压',
        backgroundColor: 'rgba(255, 99, 132, 0.6)'
      },
      {
        data: this.filteredData.map(item => item.bloodSugar),
        label: '血糖',
        backgroundColor: 'rgba(54, 162, 235, 0.6)'
      }
    ];
  }
}

5. 关键说明

  • 筛选逻辑:applyFilter方法可根据需求扩展,比如支持地点模糊匹配、多条件组合筛选等。
  • 数据转换:updateChart方法负责将表格数据映射为图表格式,可根据业务需求调整统计维度(如按日期分组统计平均值)。
  • 图表定制:通过barChartOptions可配置图表的响应式、颜色、坐标轴等细节,完全兼容Chart.js原生配置项。
  • 数据联动:filteredData同时作为表格和图表的数据源,确保两者数据完全同步。

内容的提问来源于stack exchange,提问作者Midhun Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:12:49