0

on the top of my component I have declared variable selectedTimeSlot

now, on UI I have chart which calls this method to format X axis

dateTickFormatting(val: Moment): string {
    switch(this.selectedTimeSlot) {
      case TimeSlot.Hour:
        return val.format('H');
      case TimeSlot.Day:
        return val.format('D');
      case TimeSlot.Week:
        return val.format('ddd');
      case TimeSlot.Month:
        return val.format('M');
      case TimeSlot.Year:
        return val.format('Y');
    }
  }

but this.selectedTimeSlot is undefined, how can I access my variable inside this function ?

kosnkov
  • 5,609
  • 13
  • 66
  • 107
  • is your function declared as a class method, or is it just a simple Javascript function ? – Nicolas Jan 24 '19 at 16:05
  • Can you share the wole `.ts` file? – veben Jan 24 '19 at 16:08
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Jan 24 '19 at 17:58

1 Answers1

1

Have you tried

> dateTickFormatting = (val: Moment) => { }

If it's in a class it should work with your code piece, if not then probably this gonna solve your issue.

T. L.
  • 36
  • 1
  • 4
  • 1
    great it works, can you explain why ? – kosnkov Jan 24 '19 at 16:07
  • 1
    This is an "arrow function" which doesn't create it's own scope. When you use a class, it has it's own scope (since it's actually transpiled to a normal function) and the internal methods are are hooked to the prototype. – T. L. Jan 24 '19 at 16:16