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

ngx-charts饼图onSelect仅返回name/value,如何修改返回字段?

How to Include id in ngx-charts PieGrid onSelect Event

Great question! Modifying the ngx-charts source files directly is strongly discouraged—here’s why, plus practical alternatives to get the id property in your onSelect callback:

Why You Shouldn’t Modify Source Files

  • Any npm update to ngx-charts will overwrite your changes, breaking your code unexpectedly.
  • Team members will have to replicate your local modifications, leading to inconsistent environments.
  • It creates technical debt that’s hard to maintain and debug long-term.

Better Solutions to Get the id

1. Match the Selected Event to Your Original Data (Simplest Approach)

Since the onSelect event returns name and value, you can use these properties to look up the full item (including id) from your original any[] data list. This works if name + value combinations are unique in your dataset:

// Your component code
yourDataList: any[] = [/* your data with id, name, value */];

onChartSelect(selected: { name: string; value: number }) {
  // Find the matching item in your original data
  const selectedItem = this.yourDataList.find(item => 
    item.name === selected.name && item.value === selected.value
  );

  if (selectedItem) {
    // Now you have access to the id!
    console.log('Selected item ID:', selectedItem.id);
    // Use the id for your logic here
  }
}

2. Extend the PieGridSeriesComponent (For Non-Unique Name/Value Pairs)

If your dataset has duplicate name + value combinations, you can create a custom component that extends the original PieGridSeriesComponent and overrides the onClick method to emit the full data object (including id):

// custom-pie-grid-series.component.ts
import { Component } from '@angular/core';
import { PieGridSeriesComponent } from '@swimlane/ngx-charts';

@Component({
  selector: 'app-custom-pie-grid-series',
  // Reuse the original component's template (no need to rewrite it)
  template: '<svg [attr.width]="width" [attr.height]="height" class="pie-grid-chart"><g [attr.transform]="transform"></g></svg>'
})
export class CustomPieGridSeriesComponent extends PieGridSeriesComponent {
  onClick(data: any): void {
    // Emit the full data object instead of just name/value
    const fullData = this.data[0].data;
    this.select.emit({
      name: fullData.name,
      value: fullData.value,
      id: fullData.id // Include your id property here
    });
  }
}

Then, replace the original <ngx-pie-grid-series> tag in your template with your custom component:

<ngx-pie-grid-chart [results]="yourDataList">
  <app-custom-pie-grid-series></app-custom-pie-grid-series>
</ngx-pie-grid-chart>

3. Transform the Event Stream with RxJS

If you prefer not to create a custom component, you can use RxJS operators to modify the select event stream before subscribing to it:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { PieGridChartComponent } from '@swimlane/ngx-charts';
import { map } from 'rxjs/operators';

@Component({ /* ... */ })
export class YourChartComponent implements AfterViewInit {
  @ViewChild(PieGridChartComponent) pieGridChart!: PieGridChartComponent;
  yourDataList: any[] = [/* your data */];

  ngAfterViewInit(): void {
    this.pieGridChart.select.pipe(
      map(selectedEvent => {
        const matchedItem = this.yourDataList.find(item => 
          item.name === selectedEvent.name && item.value === selectedEvent.value
        );
        // Merge the original event with the id (fallback to null if no match)
        return { ...selectedEvent, id: matchedItem?.id || null };
      })
    ).subscribe(extendedEvent => {
      console.log('Event with ID:', extendedEvent);
      // Handle the extended event here
    });
  }
}

Final Recommendation

Start with Solution 1 if your name + value pairs are unique—it’s the simplest and most maintainable. If you need to handle duplicates, go with Solution 2 for a clean, reusable component. Avoid modifying source files at all costs!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:43:48