1

on the below code snippet in custom tooltip under tooltip on click event, the class variable is not accessible when I try with this it showing values related to ChartElement only

@Output() valuechange = new EventEmitter<any>();
options: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
tooltips: {
  displayColors: false,
  mode: 'nearest',
  intersect: false,
  enabled: false,
  custom(tooltipModel: any) {
    // tooltip element
    let tooltipEl: any = document.querySelector('#chartjs-tooltip');

    // create element on first render
    if (!tooltipEl) {
      tooltipEl = document.createElement('div');
      tooltipEl.id = 'chartjs-tooltip';
      tooltipEl.style.width = '124px';
      tooltipEl.style.color = 'white';
      tooltipEl.style.borderRadius = '6px';
      tooltipEl.style.backgroundColor = 'rgba(55, 71, 79, 0.8)';
      tooltipEl.innerHTML = '<div style ="display:flex;flex-direction:column">sample tooltip</div>';
      document.body.appendChild(tooltipEl);
    }

      tooltipEl.onclick = () => {
        // NOT ABLE TO Access this to emit event 
        // this.valuechange.emit('test');
        console.log('hi); // working
      };
    }
}
  • [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) don't have [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this) defined in the way that 'normal' functions do. – timclutton Mar 25 '20 at 09:27
  • even tooltipEl.onclick = function () { // not working } – user8505818 Mar 25 '20 at 09:58

1 Answers1

2

To make this equal to the class, write it as an arrow function:

custom: () => {
 console.log(this); // should be the class
}

But sometimes you need a handle of this and that where this is the class and that is the Chart object.

Create a utility function:

export const thisAsThat = (callBack: Function) => {
    const self = this;
    return function () {
      return callBack.apply(self, [this].concat(Array.prototype.slice.call(arguments)));
    };
  }

Then:

import { thisAsThat } from './where/thisAsThat/is/located';
....
custom: thisAsThat((that: any, otherArgument: any) => {
  console.log(this); // the class
  console.log(that); // the chart object
})

TypeScript: How to use both fat arrow and this?

AliF50
  • 16,947
  • 1
  • 21
  • 37