0

I would like to insert a <script>...</script> inside a .html component in an Angular project and I was wondering how it can be done.

It seems like any Javascript I insert into this component is just ignored.

lupz
  • 3,620
  • 2
  • 27
  • 43
Mor
  • 55
  • 7
  • 1
    You can check these answers to include javascript in Angular.https://stackoverflow.com/questions/37081943/angular2-import-external-js-file-into-component – Arjun May 27 '19 at 12:46

1 Answers1

0

Yeah sure you can add javascript in Angular.You can make one external Javascript file and put all your code inside that file.For example you file is external.js in /app folder.And now you can access that file functions in Angular component.This is the easiest way I found. You can use import to include your external file. Code for that will be following.

import './external.js';
declare var myExtObject: any;

Now use one variable here I named myExtObject to call External.js file function like following any where you want :

myExtObject.func1();
Ishan Bhatt
  • 54
  • 10
  • Hi Ishan, Thanks for the reply, I apologize for my question as I am not very familiar with Angular. I need to put: import './external.js'; declare var myExtObject: any; Inside the .html file. And then in the .external.js file I put: myExtObject.func1( My Javascript Code ); ? – Mor May 27 '19 at 13:21
  • @Mor You don't need to include external.js file into your html file.You need to import external.js file in your Angular Component and angular.json as well as per your paths in application.Just import it as mentioned above and then you can use it. – Ishan Bhatt May 27 '19 at 13:33
  • But i would like to use this Javascript code only on this specific page and it should run on the Body of the page. How can it be done? I don't think I clearly understand where each code should be placed. – Mor May 27 '19 at 13:35
  • @Mor You can also include this external.js file in head of index.html file which is outside your app folder in angular project.And then you can declare variable as I have mentioned above and can use it in angular components.You can refer this link. [link](https://stackoverflow.com/questions/37081943/angular2-import-external-js-file-into-component) – Ishan Bhatt May 28 '19 at 05:56