Using a Javascript library within an Angular component: A comprehensive guide

I've been working on a Web-Client project that involves visualizing sensor data such as velocity and acceleration within a coordinate system. In order to display this coordinate system, I decided to use the graph.js library from https://github.com/dhuertas/graph.js. This library worked perfectly in a traditional index.html file with regular JavaScript, but now I'm migrating to Angular7 which uses TypeScript and Angular's component-based structure.

I've tried following various advice, like this thread: Use external javaScript library in angular 4 application, but unfortunately none of it has worked for me.

Here's what I've attempted:

The HTML code in my component:

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

The TypeScript code in my 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 is functioning properly with JavaScript, so that's not the issue here. It initializes the graph with values to be drawn.

The problem arises when I receive an error stating that graph.js is not being recognized as a module. I've even tried editing graph.js by adding export default before the definition of Graph within the file. Additionally, I've reached out to the creator via email, but haven't received a response yet.

Answer №1

Have you mentioned that?

The HTML content of my component

It is not recommended to include script code or external references in the template of a component because Angular will automatically sanitize the template and remove any scripts present in the HTML.

Instead, you can:

  1. Add the reference in the scripts array within your angular.json file, or
  2. Include the reference in the index.html file,
  3. Write a function to manually inject the script into the DOM.

Edit: Steps:

  1. Create an Assets folder within your Angular application if it does not already exist.
  2. Paste your JavaScript file into this folder.
  3. Add the path to the JavaScript file within the scripts array in the angular.json file, ensuring correct file referencing.

Your component code would resemble the 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();
}

Note: You do not need to include the line

import * as Graph from '../libraries/graph';
in your component.ts file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, o ...

Conceal the div if it remains unhidden within the following 10 seconds

This piece of code is designed to show a loader image until the page finishes loading. Here is the code snippet: document.onreadystatechange = function () { var state = document.readyState if (state == 'interactive') { $('#unti ...

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

When executing multiple promises in parallel, the function Promise.all() does not support the spread() method

I'm attempting to simultaneously run two promises using sequelize, and then display the results in a .ejs template. However, I keep encountering the following error: Promise.all(...).spread is not a function Below is my code snippet: var environme ...

Is it possible to simultaneously update two entities using a single endpoint?

In order to update data in two different entities with a @OneToOne relationship between UserEntity and DetailsEntity, I need to create a function in my service that interacts with the database. Here are the entity definitions: UserEntity @Entity() export ...

Guide on showcasing the values from two text fields with autocomplete suggestions in a third text field

Hey there, I have a search form that takes values from two text fields and combines them to populate a third text field for querying. <form name="form1" method="post" action="" autocomplete="off" oninput="sea.value = password.value +''+ passw ...

"Experience the seamless navigation features of React Navigation V6 in conjunction with

Hello there, I've been experimenting with react-navigation 6 in an attempt to show a modal with presentation: "modal" as instructed on the documentation. However, I'm facing an issue where the modal is not displaying correctly and appears like a ...

trouble with file paths in deno

I was attempting to use prefixes for my imports like in the example below: "paths": { "~/*": ["../../libs/*"], "@/*": ["./*"] } However, I keep encountering an error message say ...

Control the access to shared resources when dealing with asynchronous functions in JavaScript

Currently, I am developing a node.js server script that will utilize a shared text list for multiple clients to access asynchronously. Clients have the ability to read, add, or update items within this shared list. static getItems(){ if (list == undef ...

Mastering the process of importing AngularJS submodules in TypeScript

Currently, I am in the process of structuring an AngularJS (Angular 1) project using TypeScript. To compile TypeScript & ES6 to JavaScript, I have set up webpack. In my webpack configuration, I only compile the "app.ts" file and any other files it imports ...

What is the best way to trigger a controller action when the datepicker's value changes?

Hello, I have a custom datepicker and I am trying to perform a calculation when the year is changed. The code provided below does not seem to work on onchange. I also attempted using the onchange attribute and calling a JavaScript function like this oncha ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

Issues with the .change(function() JavaScript in Internet Explorer versions less than 9

I'm experiencing issues with this script in Internet Explorer versions below 9. Can someone please help me identify what is wrong with my script? Thank you. IE7 and IE8 are showing the following error: SCRIPT87: Invalid argument. Found ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

Utilize a module within a script in the continuous integration setup of a React application

I've created a module to verify if all the necessary environment variables are properly set in a React application. Here's a simple example of how it works: const getEnvironmentVariable = (key: string): string => { if (process.env[key]) { ...