Reputation: 1869
I've installed the dependencies I need through:
vis.js: npm install vis --save
@types/vis: npm install @types/vis --save-dev
Code snippet:
import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { Network, DataSet } from 'vis';
@Component({
selector: 'test',
template: '<div #network></div>'
})
export class TestComponent implements AfterViewInit {
@ViewChild('network') el: ElementRef;
private networkInstance: any;
ngAfterViewInit() {
const container = this.el.nativeElement;
const nodes = new DataSet<any>([
{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'}
]);
const edges = new DataSet<any>([
{from: 1, to: 3},
{from: 1, to: 2},
{from: 2, to: 4},
{from: 2, to: 5}
]);
const data = { nodes, edges };
this.networkInstance = new Network(container, data);
}
}
I tried like above just to try out but it gives me this error:
Cannot read property 'solve' of undefined
What am I missing?
Upvotes: 8
Views: 6404
Reputation: 204
I encountered the same problem when using the Vis.js Network module in my Angular project. After some searching I figured out the problem is caused by the way the Network object is constructed. If you replace this line:
this.networkInstance = new Network(container, data);
... with this line:
this.networkInstance = new Network(container, data, {});
Then the problem is solved.
Backgound
The Typescript type definitions for Vis.js have a mistake in the definition of the constructor, the definition claims that
"options" argument to the constructor is optional:
constructor(container: HTMLElement, data: Data, options?: Options);
.
But if you look into the Vis.js code you'll notice that passing an undefined options attribute causes important initialization code to be skipped, causing the error you encountered.
If instead, you pass an empty options object then the Network is initialized correctly.
Upvotes: 11
Reputation: 1211
Try to add a timeout, something like this:
ngAfterViewInit() {
const nodes = new DataSet<any>([
{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'}
]);
const edges = new DataSet<any>([
{from: 1, to: 3},
{from: 1, to: 2},
{from: 2, to: 4},
{from: 2, to: 5}
]);
setTimeout(() => {
const data = { nodes, edges };
const container = this.el.nativeElement;
this.networkInstance = new Network(container, data);
}, 0);
}
I had a similar issue which I suppose was related to the fact that I was trying to display the chart inside a tab and I had to reference it like this to add it to the event queue, so it was executed after all the other calls from the current call stack. I hope this helps.
Upvotes: 0