How to use Dracula graph library in Angular?

902 views Asked by At

I came across JS library which seems to be perfect for me https://www.graphdracula.net/
I installed needed libraries using npm - npm i raphael graphdracula. It created folders in node_modules and also updated package.json as expected
Now when I try to create graph

var g = new Dracula.Graph();

compiler complains

Cannot find name 'Dracula'

the question is how can I import library so typescript / angular knows about it ? IDE is not very helpful. I know I have to import it in my module by I don't know how to find out what to import

import { ?? } from '??'; 
2

There are 2 answers

2
Martin Čuka On

When you install js. library which is not written in typescript (does not have type definition *.d.ts) you need to import it like this:

import * as drac from 'graphdracula';

then you can use it

var g = new drac.Dracula.Graph();

You can read more about importing 3rd party libraries e.g. here: https://hackernoon.com/how-to-use-javascript-libraries-in-angular-2-apps-ff274ba601af

0
Kruupös On

First install dependencies with npm

npm install --save graphdracula raphael

Now I will translate the main example of dracula github repository into typescript for angular.

In module.component.ts:

import * as dracula from 'graphdracula';

//[...]

const Graph = dracula.Graph;
const Renderer = dracula.Renderer.Raphael;
const Layout = dracula.Layout.Spring;

const graph = new Graph();

graph.addEdge('Banana', 'Apple');
graph.addEdge('Apple', 'Kiwi');
graph.addEdge('Apple', 'Dragonfruit');
graph.addEdge('Dragonfruit', 'Banana');
graph.addEdge('Kiwi', 'Banana');

const layout = new Layout(graph);
const renderer = new Renderer('#paper', graph, 400, 300);
renderer.draw();

In module.component.html

<div id='paper'>
</div>