Using External JS File In Angular App

Angular

Simple, Angular is an open-source, client-side development framework based on typescript, developed by Google. It's very easy to learn and very easy to implement. Moreover, the angular community is very strong.

Create an angular app

I will use angular CLI to create a new app. Open command prompt and execute this command > ng new app

Now open the project in vs code editor and serve by ng server command. 

Add externaljs file

Step 1

Take a file in the assets folder and set any name. Like as custom.js 

function getToday() {
    alert(new Date().toLocaleDateString());
}

function greetings(name) {
    alert(`wellcome ${name}`);
}

Step 2

Now add the customjs file reference in the angular.json scripts section array list. Like as below

"src/assets/custom.js"

Step 3

Now add the functions reference in a component file. I am using the app component.ts

//external js function declaration
declare function getToday(): any;
declare function greetings(name: any): any;
ngOnInit(): void {
    // call the externaljs functions
    getToday(); // without param
    greetings('rohol'); // with param
}

Now again serve the app and get the result.

Happy coding and thanks for reading my article.


Similar Articles