Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use external javaScript library in angular application

I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with <script src="assets/js/timeline.js"></script> and in app.component.ts, I have :

var timeline = new Timeline("timelineVisualization") 

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

like image 540
Adrien Avatar asked Jul 06 '17 10:07

Adrien


People also ask

How do I use an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can I use JavaScript in angular 13?

The Angular 13 update adds RxJS, a reactive extension for JavaScript, and includes all versions of RxJS up to and including version 7. For apps created with ng new, RxJS 7.4 has become the default.


2 Answers

you simply need to do

 import * as Timeline from '../assets/js/timeline.js'; 

You can also do (at the top of your file) :

declare var Timeline: any; 

Check also below for good practices.

like image 156
Deblaton Jean-Philippe Avatar answered Oct 09 '22 09:10

Deblaton Jean-Philippe


Just extending on the above answer by @Deblaton Jean-Philippe and as a general good practice, it might be better to include your js or other css files as part of the build instead of putting them in your index.html.

If you are using a bundler, use something like this.

  "styles": [     "styles.scss",     //Other style files   ],   "scripts": [     "../node_modules/jsplugin/dist/js/plugin.js",     //Other script files   ], 
like image 31
Srikkant Srinivasan Avatar answered Oct 09 '22 10:10

Srikkant Srinivasan