How to use external JS files and JavaScript code in Angular 6/7

Posted at: February 1, 2019 3:27 PM

In this tutorial you can learn how to use external js files and how to use JavaScript code in Angular 6/7. We have taken example of add jquery and bootstrap library and create custom JavaScript file and create function and use this custom function in specific component.

Add external JS files

If you want include any js library in your angular application like as jquery, bootstrap etc.. You can use npm command for install this library.

For example we are installing jquery and bootstrap library:

After installing this library add them in styles and scripts array in angular.json respectively css and js. You can see in build: { } object.

Add custom JavaScript files

If you want to add custom JavaScript file in your application then copy or create own js file in src/assets. Best way you can organize file in src/assets folder according file type like as JavaScript file keep in js folder.

For example I have created custom.js file in folder src/assets/js and add both JavaScript and jquery code.

src/assets/js/custom.js

And add this JavaScript file in scripts array in angular.json file like as above you have added jquery library.

Full code of angular.json

How to use JavaScript code in angular 6 / 7

You can easily use JavaScript function in your specific component file.

For example I am using function myTest() in src/app/app.component.ts and call this function on button click event.

src/app/app.component.ts

Full code

src/app/app.component.html

Conclusion

In this tutorial you have learn how to add external js file and custom JavaScript code in specific component in your angular application with help of example of add jquery and bootstrap library and custom JavaScript file.

External Js Files Custom Js Files JavaScript Code in Angular Component

Please leave comments

16 Comments

truecodex launched free android app. You can download and install truecodex app on your mobile and get notification of the latest post.

Video Tutorials on YouTube