Using external JS Files in Angular

Hi guys! How are you ? Today I’m writing about Angular and how we have to do to use Javascripts features in our projects.

Let’s go 😉

First, we have three goals today:

  1. Use some functions from our custom.js
  2. Use the global object declared iron-rules.js
  3. Integrate Jquery in our Project

Using JS functions 😉

We have this js file:

custom.js is in assets/js directory. This file has 3 elementary functions:

  • sayHelloTo(name)
  • logName(name)
  • doSomething()

We have to use them in our component but how can we do that ?

First, we need to declare custom.js in our angular.json file to do it global and accessible in all our application.

Second, we need to reference each function in our component 😉 It’s important that we use the same name declared in the js file.

Finally, we call our 3 functions in the function onClickSayHello();
Magic, works 😀

Using global object declared in JS file 😉

We have an external js file with an object inside it with many functionalities that we want to use.

IronValidator is a JS Object with two methods:

  1. validateName
  2. validateNBusinessRules

We want to use both to validate business rules in our component but we need to import ironValidator object, how can we do that? 🙁

First, we need to import iron-rules.js file in our angular.json.

Second, we need to declare the ironValidator variable in our component and use it but remember it’s important to use the same name declared in the jsFile. For this reason, the variable’s name must be: ironValidator.

Finally, we can use the ironValidator object and his methods 😉

Integrating JQuery 😮

Sometimes, we need to use Jquery to do some operations but it’s not bad! some developers think that jquery is the worst bad practice in the world and that’s no true. JQuery is a great library and in small projects can be useful in these times too 😉
In Angular Real Life, we often need to work with Jquery templates and we have to know to integrate this library in our projects. Let’s go 😉

First, we need to install Jquery:

npm install jquery

Second, we need to declare this script in our angular.json.

Third, we have to reference this JQuery in our component:

Finally, we use Jquery to retrieve say-hello-id textbox’s value 😉

Demo prints 😀

App greetings 😉 We can see a simple view with a textbox and a button. When the user press the button, our onClickSayHello() function will be called.

I type my name and touch the button and magic 😉

We can see how all external JS Functions are called 😉

Resume:

  1. Install JS package OR put JS Files in a directory.
  2. Declare JS files in the angular.json
  3. Declare function / object in the component

That’s all 😉

All the code is on my github, just check it 😉