On selectionChanged function, 'this' is undefined ?!?

I’m using angular 2, and I need to update ‘selectedData’ property of the component when a node in selected.

Unfortunately, I’m getting an exception:
"Cannot set property ‘selectedData’ of undefined"

this is the relevant code:

export class FlowComponent implements AfterViewInit {
  selectedData: any;

AfterViewInit () {

const diagram = $(go.diagram, this.element.nativeElement,
{  ... }
);

diagram.model = $(go.GraphLinksModel, { ... } );

 diagram.nodeTemplate =
    $(go.Node, "Spot",
       {
          selectionChanged: this.onSelectionChanged
       },
       ...
    );
  }

  onSelectionChanged(node: go.Node) {
    if (node.isSelected) {
      this.selectedData = node.data;
    }
  }

...
}

I tried to change it to “this.onSelectionChanged.bind(this)” or to anonymous function, both failed.

Why am I getting this error?

what can I do?

Thanks.

What would you expect this to be?

No event handlers and listeners in GoJS are called binding this. They all can be JavaScript arrow functions, with whatever closed-over variables that you like.

I expect this to be the component that the method is part of, as is customary in Angular 2.
I have to set the class’ selectedData property, How can I solve this?

  {
    selectionChanged: n => { if (n.isSelected) this.selectedData = n.data; }
  }

As I said, I already tried this approach (anonymous function), and had the same error…

Do you understand the difference between anonymous functions and arrow functions in JavaScript? Specifically in the interpretation of this, which is lexically scoped in arrow functions, but which is bound by the caller in anonymous functions.

What is the code that you are trying? Show everything from the top of the file, but elide everything that is unrelated to the problem.

Tried it again, it works. Thank you!