我正在对graphing library Vis.JS进行一些适合性测试。我已将它与Angular2集成,但是我想在点击网络元素时调用angular2组件函数。这是我生成基本网络图的组件:
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');
});
}
}
而不是
network.on("click", function (params) {
window.alert('onclick');
});
我想做一些像
这样的事情network.on("click", function (params) {
this.myComponentFunction(params);
});
但这是将angular2与jquery方法混合在一起......我该怎么做呢?
答案 0 :(得分:0)
我把它更改为:
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]]);
}
我认为问题是当方法看起来像这样:
function (params) {
window.alert('onclick');
}
'this'关键字的范围是内部函数,我无法引用任何组件成员。