2

Question might be easy but I'm quite stuck with it.

I have a chartjs options object. There is a callback function within it.

I need to use some component's variable in that function (this.period).

Is something like this possible ?

Component code:

 @Input() period: string;

 public lineChartOptions: any = {
    responsive: true,
    // maintainAspectRatio: false
    scales: {
      xAxes: [{
        ticks: {
          max: 10,
          callback: (function(value, index, values) {
            this.wrapperXAxisCallback(value, index, values)
          })
        }
      }],
    }
  };

  wrapperXAxisCallback(value, index, values) {
    switch (this.period) {
      case '24hr':
        ..... break;
      case 'week':
        ..... break;
    }
  }
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
user1935987
  • 3,136
  • 9
  • 56
  • 108

2 Answers2

4

You want to use an arrow function so you can access your component (this) into the callback function.

public lineChartOptions: any = {
responsive: true,
// maintainAspectRatio: false
scales: {
  xAxes: [{
    ticks: {
      max: 10,
      callback: ((value, index, values) => {
        this.wrapperXAxisCallback(value, index, values)
      })
    }
  }]
}
  };

Check the full reference here :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Sorikairo
  • 798
  • 4
  • 19
  • @user1935987 who said development has to be hard ? :D Anyway, if it fix your problem, accept an answer, either mine or Chellapan's one as we said the same thing :) – Sorikairo Oct 09 '18 at 15:02
3

Try this

public lineChartOptions: any = {
    responsive: true,
    // maintainAspectRatio: false
    scales: {
      xAxes: [{
        ticks: {
          max: 10,
          callback: ((value, index, values)=>{
            this.wrapperXAxisCallback(value, index, values)
          })
        }
      }],
    }
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60