[Chartjs]-Is there a way to call a Component's function from click function of Chartjs

4👍

Yes, you can bind. But chartjs plugin is element based. So you need to write a directive to implement to apply any jQuery or element based approach.

Here is the solution for your question.
Here the trick is assign a component this to some other variable and access it inside a the chartjs click function. After that you can pass any data you want.

    ngAfterViewInit() {
    this.canvas = this.mychart.nativeElement; 
    this.ctx = this.canvas.getContext('2d');
    let $this = this;
    let myChart = new Chart(this.ctx, {
      type: 'bar',

      data: ...,
      options: {
          legend : {
            display: true
          },
          responsive : true,
          scales : {
            xAxes :[{
              ticks:{
                beginAtZero: true
              }
            }]
          },
          onClick: function (e) {
            debugger;
            var element = this.getElementAtEvent(e);
            if (element.length) {
               console.log(element[0]._view.label)
            }
            $this.Showtest(e, this, element);
          },
          //onClick: this.Showtest.bind(this),
        }
    });
  }

  Showtest(event, chart, element) : void {
    debugger;
  }

Leave a comment