我在我的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)
}
}
在这里,我创建了chartClicked函数,希望在那里获得点击条数据集和标签值.
例如,在下面的屏幕截图中,如果我单击粉色条,我希望得到
MTB
和值3