Jonathan Jost
Jonathan Jost

Reputation: 23

How to use Javascript Library in Angular Component

I am building a Web-Client, which is supposed to visualize Sensor data (velocity, acceleration) inside a coordinate system. To display the coordinate system i used the library graph.js from here https://github.com/dhuertas/graph.js , which worked perfectly fine with a classic index.html and normal javascript, but I want to use Angular7 , which does use TypeScript and Angulars Compnent app structure...
I already tried this: Use external javaScript library in angular 4 application (which is basically exactly what I need) and a couple of similar threads but none did work for me

What I did was the following :

the HTML of my component

<div style="position:relative;top:100px;left:950px" id='container' class="trajStrly"></div>
<script type="module" src="../libraries/graph.js"></script>

parts the component.ts:

import * as Graph from '../libraries/graph';
declare var Graph: any;

// ... inside the component Class...
    graph: any;

    ngOnInit() {
        this.graph =  new Graph({
            appendTo : "container",
            canvasWidth : 100,
            canvasHeight : 100,
            colorList : ["#666666","#666666","#00F"],
            xAxisTitle : "X",
            yAxisTitle : "Y"
        }); 
    this.draw();
  }

the draw function worked fine with the JavaScript and is not the probloem here. It initializes the graph with values to draw.

The Error I get is that graph.js is not a module. I already tried editing graph.js by putting export default in front of the definition of Graph inside grapf.js. Also already emailed the creator, but he did not answer me yet

Upvotes: 1

Views: 1355

Answers (1)

j4rey
j4rey

Reputation: 2677

Did you say?

the HTML of my component

You cannot place scripts code or source references in component template as Angular will automatically sanitize the template and remove any scripts in the template html.

What you can do is

  1. Add the reference it in the scripts array in angular.json file, or
  2. add the reference in the index.html file
  3. write a code to manually inject the script in the DOM

Edit: Steps:

  1. Create Assets folder an your angular application is it doesn't already exists.
  2. Copy-paste your js file there.
  3. Add the js file path in the scripts array in angular.json file, make sure you point to the correct file.

Your component code will be like following

declare var Graph: any;
graph: any;

ngOnInit() {
    this.graph =  new Graph({
        appendTo : "container",
        canvasWidth : 100,
        canvasHeight : 100,
        colorList : ["#666666","#666666","#00F"],
        xAxisTitle : "X",
        yAxisTitle : "Y"
    }); 
    this.draw();
}

Notice: no need to add this line in your component.ts import * as Graph from '../libraries/graph';

Upvotes: 1

Related Questions