jquery Angular 9 chart.js条形图Click event

u3r8eeie  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(101)

我在我的Angular 9应用程序中使用了chart.js
这里我想得到点击栏数据集和标签值。
这是我的示例代码

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public barChartOptions: any = {
    responsive: true,
    scaleShowVerticalLines: false,
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      xAxes: [
        {
          stacked: true,
          ticks: {
            beginAtZero: true,
            maxRotation: 0,
            minRotation: 0,
          },
        },
      ],
      yAxes: [
        {
          stacked: true,
        },
      ],
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
        font: {
          size: 10,
        },
      },
    },
  };

  public barChartLabels: string[];
  public barChartType: string = 'bar';
  public barChartLegend: boolean = true;

  public barChartData: any[] = [];

  ngOnInit() {
    /**My APi result */
    let data = [
      {
        operatorName: 'MBT',
        label: 'Application',
        subLabel: 'Positive',
        count: 1,
      },
      {
        operatorName: 'MBT',
        label: 'Channels',
        subLabel: 'Negative',
        count: -1,
      },
      {
        operatorName: 'MBT',
        label: 'Customer Care',
        subLabel: 'Negative',
        count: -1,
      },
      {
        operatorName: 'MBT',
        label: 'Customer Care',
        subLabel: 'Positive',
        count: 1,
      },
      {
        operatorName: 'OTS',
        label: 'Application',
        subLabel: 'Negative',
        count: -1,
      },
      {
        operatorName: 'OTS',
        label: 'Application',
        subLabel: 'Positive',
        count: 1,
      },
      {
        operatorName: 'OTS',
        label: 'Channels',
        subLabel: 'Positive',
        count: 1,
      },
      {
        operatorName: 'OTS',
        label: 'Customer Care',
        subLabel: 'Positive',
        count: 1,
      },
    ];

    /**Implement Logic here */
    let labels = [...new Set(data.map((x) => x.label))];
    //let operators = [...new Set(data.map((x) => x.operatorName))];
    let subLabels = data.reduce((acc, cur: any) => {
      if (
        acc.findIndex(
          (x) =>
            x.operatorName == cur.operatorName && x.subLabel == cur.subLabel
        ) == -1
      )
        acc.push({ operatorName: cur.operatorName, subLabel: cur.subLabel });

      return acc;
    }, [] as { operatorName: string; subLabel: string }[]);

    let subLabelDatasets = subLabels.map((x) => {
      let datasets = [];
      let opratorlabes = [];
      for (let label of labels) {
        datasets.push(
          data.find(
            (y) =>
              y.label == label &&
              y.subLabel == x.subLabel &&
              y.operatorName == x.operatorName
          )?.count || 0
        );
      }

      return {
        label: x.operatorName + ' ' + x.subLabel,
        data: datasets,
        stack: x.operatorName,
        type: 'bar',
      };
    });

    this.barChartLabels = labels;
    this.barChartData = subLabelDatasets;
    
  }

  /*On click logic */
  chartClicked(event:any){
    console.log(event)
  }
}

字符串
stackblitz
在这里我创建了chartClicked函数,我想获得点击栏数据集和标签值。
例如下面的截图,如果我点击粉红色的颜色条,我想得到MTB和值3


的数据

ztyzrc3y

ztyzrc3y1#

从 * ng 2-charts* 尝试使用BaseChartDirective,但似乎无法获取图表示例,甚至没有BaseChartDirective,我也无法在onclick函数中获取chart示例。不确定是否是版本(1.6)问题。
因此,我建议使用 * chart.js * 库来生成图表,以便能够获得图表示例,而不是使用 * ng 2-charts* 库。
这需要一些更改才能从 * ng 2-charts* 迁移到 * chart.js *。
通过 * chart.js * 生成图表:

public barChartOptions: any = {
    responsive: true,
    scaleShowVerticalLines: false,
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      x: {
        stacked: true,
        ticks: {
          beginAtZero: true,
          maxRotation: 0,
          minRotation: 0,
        },
      },
      y: {
        stacked: true,
      },
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
        font: {
          size: 10,
        },
      },
    },
    onClick: function (evt, elements, chart) {
      const bars = chart.getElementsAtEventForMode(
        evt,
        'nearest',
        { intersect: true },
        true
      );
      if (bars.length === 0) return; // no bars

      const bar = bars[0];

      // Get index and label text
      const index = bar.index;
      const label = chart.data.labels[index];
      let selectedDataset = chart.data.datasets[bar.datasetIndex];

      console.log('Selected label:', label);
      console.log('Selected sub-label:', selectedDataset.label);
      console.log("Selected sub-label's value:", selectedDataset.data[index]);
    },
  };

ngOnInit() {
  new Chart('baseChart', {
      type: <ChartType>this.barChartType,
      options: this.barChartOptions,
      data: {
        datasets: this.barChartData,
        labels: this.barChartLabels,
      },
    });
}

个字符
在上面的代码中,您需要onclick函数和getElementsAtEventForMode方法来获得所选的条形图,这要归功于answer on ChartJs how to get from multiple dataset which dataset bar is clicked
Demo @ StackBlitz

相关问题