Invoke Angular2 Component function from VisJS Event

1k views Asked by At

I'm doing some suitability testing on a graphing library Vis.JS. I've got it integrated with Angular2, however I'd like to call an angular2 component function when the network element is clicked. Here is my component that produces a basic network diagram:

import {Component, OnInit, ViewChild, ElementRef} from '@angular/core'

//reference to visjs library
declare var vis: any;

@Component({
    selector: 'visjs',
    templateUrl: './app/visJs/visjs.basic.html'
})

export class VisJsBasicComponent implements OnInit {

    @ViewChild('network') _element: ElementRef; 

    ngOnInit() {

        this.createBasicNetwork();
    }

    createBasicNetwork(): void{
        // create an array with nodes
        var nodes = new vis.DataSet([
            { id: 1, label: 'Node 1' },
            { id: 2, label: 'Node 2' },
            { id: 3, label: 'Node 3' },
            { id: 4, label: 'Node 4' },
            { id: 5, label: 'Node 5' }
        ]);

        // create an array with edges
        var edges = new vis.DataSet([
            { from: 3, to: 1 },
            { from: 1, to: 2 },
            { from: 2, to: 4 },
            { from: 2, to: 5 }
        ]);

        //create the network
        var data = {
            nodes: nodes,
            edges: edges
        };
        var options = {};
        var network = new vis.Network(this._element.nativeElement, data, options);

        network.on("click", function (params) {
            window.alert('onclick');
        });
    }
}

instead of

network.on("click", function (params) {
            window.alert('onclick');
        });

I'd like to do something like

network.on("click", function (params) {
        this.myComponentFunction(params);
});

but this is mixing angular2 with jquery methods... How do I go about this?

1

There are 1 answers

0
cobolstinks On BEST ANSWER

I changed it to this:

var network = new vis.Network(this._element.nativeElement, data, options);

network.on('click', (params) => {
   if (params && params.nodes && params.nodes.length === 1) {
      this.nodeClicked(params);
    } else {
       console.log('non node element clicked');
    }
});    
}

nodeClicked(params: any): void {
   this._router.navigate(['/Node',params.nodes[0]]);
}

I think the issue was that when the method looked like this:

function (params) {
            window.alert('onclick');
        }

the 'this' keyword was scoped to the inner function and I couldn't reference any component memebers.