0

I have an Angular 6 app that uses the excellent ngx-charts framwork to display charts. This charting component lets me specify a tooltip formatting function like so:

<ngx-charts-bar-vertical [xAxisTickFormatting]="dateTickFormatting" >
</ngx-charts-bar-vertical>

And then define the formatting function in the parent component class:

  dateTickFormatting(val: string): string {
    return val.toUpperCase();
  }

My problem happens when I try to access values in the parent component class from this formatter function:

  public testVar: string = 'This is a test variable';

  dateTickFormatting(val: string): string {
    console.log(this.testVar);
    return val.toUpperCase();
  }

In this case, testVar will be undefined.

I understand that the 'this' reference is lost because ngx-charts is referencing dateTickFormatting as a 'raw' function. Is there a way to preserve a reference to the parent classes' this, barring modifications to the charting framework?

caitlin
  • 2,769
  • 4
  • 29
  • 65

1 Answers1

2

You should use arrow functions

If you do

  public testVar: string = 'This is a test variable';

  dateTickFormatting = (val: string): string => {
    console.log(this.testVar);
    return val.toUpperCase();
  }

It will use the correct this and work.

I recommend reading a bit about arrow functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Dinosan0908
  • 1,082
  • 2
  • 8
  • 19