Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call external javascript function in angular 5?

I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

like image 984
Milan Avatar asked Nov 17 '17 08:11

Milan


People also ask

Can we add JavaScript in angular?

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. After installing this library add them in styles and scripts array in angular. json respectively css and js.


1 Answers

You can use javascript in the Angular application.

Step 1. Create demo.js file in assets/javascript folder.

export function test1(){
    console.log('Calling test 1 function');
}

Step 2. Create demo.d.ts file in assets/javascript folder.

export declare function test1();

Step 3. Use it in your component

import { test1 } from '../assets/javascript/demo'; 
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}

Note: js and .d.ts file name should be same

like image 50
Akshay Garg Avatar answered Oct 09 '22 19:10

Akshay Garg