Chartjs-Angular | Access a variable in a function

2👍

Either change the anonymous functions to fat arrow syntax

dragData: {
  dragX: true,
  onDragStart: (e: Event) => {
    console.log(e)
  },
  onDrag: (e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) =>  {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  },
  onDragEnd: (e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) => {
    this.isOnDrag = false; // I want to edit this global var
  },
},

or .bind(this) to the functions.

dragData: {
  dragX: true,
  onDragStart: function(e: Event) {
    console.log(e)
  }.bind(this),
  onDrag: function(e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  }.bind(this),
  onDragEnd: function(e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) {
    this.isOnDrag = false; // I want to edit this global var
  }.bind(this),
},

1👍

change your function definition. You need to define your functions as an Arrow function:

dragData: {
  dragX: true,
  onDragStart: (e: Event) => {
    console.log(e)
  },
  onDrag:(e: Event, datasetIndex: any, index: any, value: { x: number; }) => {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  },
  onDragEnd:(e: Event, datasetIndex: any, index: any, value: { x: number; }) => {
    this.isOnDrag = false; // I want to edit this global var
  },
},

As I understand Your isOnDrag property is defined in your class.
when you are defining your functions in regular way function name() {} inside the Object. The this property is the object where the function is defined.

Leave a comment