我在我的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
的数据
1条答案
按热度按时间ztyzrc3y1#
从 * ng 2-charts* 尝试使用
BaseChartDirective
,但似乎无法获取图表示例,甚至没有BaseChartDirective
,我也无法在onclick
函数中获取chart
示例。不确定是否是版本(1.6)问题。因此,我建议使用 * chart.js * 库来生成图表,以便能够获得图表示例,而不是使用 * ng 2-charts* 库。
这需要一些更改才能从 * ng 2-charts* 迁移到 * chart.js *。
通过 * chart.js * 生成图表:
个字符
在上面的代码中,您需要
onclick
函数和getElementsAtEventForMode
方法来获得所选的条形图,这要归功于answer on ChartJs how to get from multiple dataset which dataset bar is clicked。Demo @ StackBlitz的