When you want to integrate external libraries with Angular, you also need to remember that Angular uses Typescript and typescript is a typed language that compiles to Javascript and because of that we need to declare classes, so Typescript can be compiled with no errors.

But how can we do that? I’ve created a project on my Github that shows that, but I would like to give some explanations here, so that code can be better understood.

I assume that you have a angular project already set up, so what we need to do now is install mxgraph:

npm install mxgraph — save

After you’ve installed mxgraph we need to configure Angular, so it imports our library. Go to angular.json and add the following code:

We changed the assests and the scripts properties, to the scripts we added two js files, mxgraph.conf.js that contains some mxgraph configuration and the mxClient.js that is mxgraph library. With these two lines, we are saying to angular to bundle together our scripts.

The second change we’ve made is to the assets property, with these changes we can be explicitly to where we want to dump the scripts, in our case, we want to dump all the assets that mxgraph provide to “/assets/mxgraph” folder.

Now we can use mxgraph with angular, but wait, how can we import the classes from mxgraph? mxGraph has no typescript implementation, so we need to declare the classes ourself, but because I am lazy, I’ve just copied the declarations from another project that is on github https://github.com/gooddaytoday/mxgraph-typescript-definitions.

I’ve copied all the files from the link above to a folder that I called mxtypes, with all files in place I had to inform typescript to compile these files, so I created new file mxtypes.d.ts that references all the other files.

/// <reference path="./mxtypes/Handlers.d.ts" />

/// <reference path="./mxtypes/Model.d.ts" />

/// <reference path="./mxtypes/mxGraph.d.ts" />

/// <reference path="./mxtypes/Shape.d.ts" />

/// <reference path="./mxtypes/Util.d.ts" />

/// <reference path="./mxtypes/View.d.ts" />

In this way, we can create graphs using mxgraph:

All the code is hosted on https://github.com/diegogusava/angular-mxgraph