2

I am new to Angular(6) and I want to know where to add page specific script in angular 6, which I have placed earlier in .cshtml file?

I have found many ways to include external JS file in Angular, but I want to add a small piece of javascript code (mentioned below) into page (or component) and of course I do not want to create a separate JS file for this small script. I have already tried to put below mentioned script literally in .html file in a component but nothing happened. I checked source code also, script was not there. Help me to understand it. Thank you.

<script type="text/javascript">
toolTip();
</script>
musigh
  • 167
  • 1
  • 3
  • 13
  • An Angular component is always defined in typescript (or javascript), where the template-url for the html-file is defined as well. My question is: if you don't already have a ts/js file that initializes the component, how do you initialize it? – ShamPooSham Sep 27 '18 at 08:19
  • Did you see this,https://medium.com/@davembush/adding-css-and-javascript-to-an-angular-cli-project-2b843a8283f3 – core114 Sep 27 '18 at 08:25
  • See this: https://stackoverflow.com/questions/44204417/dynamically-load-external-javascript-file-from-angular-component/44276683#44276683 or add your script in index.html – Ashish Ranjan Sep 27 '18 at 08:27

1 Answers1

1

From my point of view - the best way how to do this - is to locate your script in some common directory and include it into angular-cli config, if you use it:

"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js",
    "./src/common/toolTipScript.js"
],

And then use it in application wherever you need it

Sh. Pavel
  • 1,584
  • 15
  • 28
  • 1
    Then it will load for every component?! which makes a page heavy because of unnecessarily inclusion of files. Like normally, in an HTML page in a project, I want to use a plugin, but not in other HTML pages in that project. then why I will put that plugin at root level in that project for every page? though I need it for a single page. Please correct me if I am wrong. – musigh Sep 27 '18 at 08:51
  • You just include it once in the project and you do not need to load it in each component. If you want it on the one place then use it on the one place. It would not be heaviest because if you will add that script into one component it would be the same. In other words, in both methods you will load script just ones. – Sh. Pavel Sep 27 '18 at 08:55
  • ok. I'm going to try it and just to confrim angular-cli config means angular.json file. right? – musigh Sep 27 '18 at 09:06
  • angular-cli.json – Sh. Pavel Sep 27 '18 at 09:07
  • There is no file like 'angular-cli.json'. Just want to let you know again, I am using Angular version 6 and I have found Scriprt[] in angular.json?! – musigh Sep 27 '18 at 09:20