Juicy Juicy - 4 months ago 12
TypeScript Question

Accessing component properties from jQuery or other events

I'm trying to use

(or jQuery) click events in an Angular2 component. I have my graph displaying just fine, and I can successfully catch click events.

However, within the context of click events, I loose my references to my component's properties. For example,
from within the event:

export class GraphContainerComponent implements OnInit {
private visData: {};
private options: {} = {};
private network: any;
@ViewChild('graphContainer') graphContainer;

ngOnInit() {
// populates this.visData
// this.visData = { nodes, edges }

makeGraph() {
// no problem creating and displaying my graph, everything works
this.network = new vis.Network(this.graphContainer.nativeElement, this.visData, this.options);

// click event
this.network.on("selectNode", function (params) {
console.log(this.visData); // logs "undefined"

$('a').on('click', function() {
console.log(this.visData); // "undefined" as well

I understand why this is normal behavior, and I know mixing Angular2 and jQuery or some other DOM-manipulating library is not recommended practice, but sometimes it's all you got.

What's the best way to maintain a reference to my component's properties from within these events?

Crucially, there are dozens of these components on my page, so I don't think some kind of global storage is the way to go.


try to use arrow function (()=>) as shown below,

this.network.on("selectNode", (params)=> {  //<----this should work.
        console.log(this.visData); // logs "undefined"

$('a').on('click', ()=> {                   //<----this should work.
            console.log(this.visData); // "undefined" as well