0

Hi i'm trying to use viser-ng and I need to call a function onClick event.

But when I try to use this inside my calling function I am getting an error this is undefined.

<v-chart [forceFit]="forceFit" [height]="height" [data]="data" [onClick]="clickbar"></-chart>

In my component

clickbar(e: any) {
    console.log('clickbar', e.target); // return clicked data
    console.log("this", this); // return undefined

    this.openDialog(e.data._origin) // error
}

openDialog(data): void {
  console.log(data) // error
}

Can you explain me how can I call my openDialog function ?

Trying (click)="clickbar($event)" but $event return mouseevent not clickedData

M.Hol
  • 365
  • 2
  • 4
  • 15

2 Answers2

2

In your component, try to define a variabile containing this.

For example

public thisRef;


constructor(){
    this.thisRef = this;
}

And in the HTML you should be able to do

<v-chart [onClick]="clickbar.bind(thisRef)">...

This way you're binding the thisRef(which is indeed this) to this inside of your function.

Luca De Nardi
  • 2,280
  • 16
  • 35
  • You're welcome :) In case you needed to pass additional parameters to the function, you can do that inside the `bind` function like this `myFunction.bind(thisRef, param1, param2, ...., paramN)` – Luca De Nardi Aug 13 '19 at 13:28
  • I believe the reason this happens is because this is being passed as a plain javascript function so you lose the context of 'this'. Another way to solve this issue is to define your method like so: clickBar = (e: any): void => {}. Now this is set in the proper context – Mickers Aug 13 '19 at 13:32
0

I believe you are using an Input binding "Square Brackets: []" and want to be using the event binding "Round brackets: ()" like so:

<v-chart [forceFit]="forceFit" [height]="height" [data]="data" (click)="clickbar($event)"></-chart>

EDIT:

It looks like there is an @Input for the data on the controller and change the signature of the openDialog:

In component.ts file

@Input data: any; // This should already exist given the v-chart HTML

openDialog(): void {
  console.log(this.data) // error
}

In HTML file

<v-chart [forceFit]="forceFit" [height]="height" [data]="data" (click)="openDialog()"></-chart>
Joshua Loader
  • 384
  • 1
  • 5