How to call external javascript function in angular 5?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 04:23:49

问题


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.


回答1:


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




回答2:


You need to change the order in which you load your JavaSciprt files. Try loading common.js before main......js. Your script tries to access a function from a file that hasn't been loaded yet. Try just switching those two lines of code:

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



回答3:


In Angular4, 5 project folder, there is .angular-cli.json file.

In file, you will see

"apps": [
  {
    "scripts": []
  }
]

push your external js file path in the array.




回答4:


You can call these methods by window object-

document.addEventListener("DOMContentLoaded", function (event) {
      window['navbarToggleSidebar']();
      window['navActivePage']();
 });


来源:https://stackoverflow.com/questions/47346559/how-to-call-external-javascript-function-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!