Richard77
Richard77

Reputation: 21661

Where to place custom js files and how to reference them in Angular 4 application

Let's say I acquired a html5 template. The folder that contains HTML, css, js files, and other types of resources like pictures. I copied/pasted the Html and css to component.html and component.css.

When it comes to JavaScript, I have a folder called js containing few individual JavaScript files.

Where should I place the js folder and how to do I reference them in my application?

In the original file I have something like all the way to the bottom of the HTML file:

<script src="js/script1.js"></script>
<script src="js/script2.js"></script>
<script src="js/script3.js"></script>

Thanks for helping

Upvotes: 1

Views: 749

Answers (2)

VithuBati
VithuBati

Reputation: 1928

you have two choices

1 you can place it inside body tag in index.html like this

<body>
<app-root></app-root>
<script type="text/javascript" src="assets/jquery/jquery.min.js">
</script>
<script type="text/javascript" src="assets/js/script2.js">
</script>
</body>

2 you can place it inside scripts in .angular-cli.json file like this

"scripts": [
    "./assets/js/script2.js"
    "assets/jquery/jquery.min.js"
  ],

and if you want to access the code inside the component, declare a global variable just under the import statement and above the component declaration like this

import { Component } from '@angular/core';
declare const $: any;
@Component({
  selector: 'tc-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  showModal(){ 
  //caling jQuery method
   $("#modalId").show();
 }
}

Upvotes: 2

Bk Santiago
Bk Santiago

Reputation: 1573

You can put it under src/assets/js/script1.js

Then add it on .angular-cli.json

"apps": [
  {
    ...
    "scripts": [
      "assets/js/script1.js"
    ]
  }
]

To access your code on your typescript code,

you can access it globally via

declare const globalVar: any;

Upvotes: 4

Related Questions