Chart.js & Angular 2 - ng2-charts Custom on Click Event

僤鯓⒐⒋嵵緔 提交于 2019-12-21 17:08:53

问题


I am trying to implement ng2-charts in my Angular 2 project and I was wondering about creating custom onclick events. Meaning, I want to override the current onclick events on the carts to do some custom functions (redirect to a page, have a modal show up, etc).

Is there a simple way to do this? Is it built in at all?

Any insight would be appreciated it


回答1:


Try to read DOCS

They have pretty good and understandable explanation of use.

There-are built-in 2 event handlers:

Events

chartClick: fires when click on a chart has occurred, returns information regarding active points and labels

chartHover: fires when mousemove (hover) on a chart has occurred, returns information regarding active points and labels


In code it looks like that:

 <base-chart class="chart"
            [datasets]="lineChartData"
            [labels]="lineChartLabels"
            [options]="lineChartOptions"
            [colors]="lineChartColours"
            [legend]="lineChartLegend"
            [chartType]="lineChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></base-chart>
  </div>

that chartHovered and chartClicked are your custom functions, which could has another names, and do custom things like showing modal, redirect to url etc.




回答2:


I found this solution at https://github.com/valor-software/ng2-charts/issues/489

public chartClicked(e: any): void {
if (e.active.length > 0) {
const chart = e.active[0]._chart;
const activePoints = chart.getElementAtEvent(e.event);
  if ( activePoints.length > 0) {
    // get the internal index of slice in pie chart
    const clickedElementIndex = activePoints[0]._index;
    const label = chart.data.labels[clickedElementIndex];
    // get value by index
    const value = chart.data.datasets[0].data[clickedElementIndex];
    console.log(clickedElementIndex, label, value)
  }
 }
}



回答3:


 public chartClicked(e: any): void {
     console.log(e);
 }

e.active[0]._model and e.active[0]._view contain information about the part of the chart you clicked (i.e. label).




回答4:


I hope my answer is correct. After much searching for the only solution I found was:

public chartClicked(e:any):void {

if(e.active.length > 0){
  var points = [];
  var pointSelected = e.active[0]._chart.tooltip._model.caretY;
  var legends = e.active[0]._chart.legend.legendItems;

  for (var i = 0; i < e.active.length; ++i) {
    points.push(e.active[i]._model.y);
  }

  let position = points.indexOf(pointSelected);
  let label = legends[position].text

  console.log("Point: "+label)
}}


来源:https://stackoverflow.com/questions/38378984/chart-js-angular-2-ng2-charts-custom-on-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!