简体   繁体   中英

How to import or use external JS files and functions in my angular web application

I want to integration external code (html, js and css files) into my angular web application.

in this external code, the HTML files is just like this:

index.html

<html>
<header>
</header>
<body>
</body>

 <script src="app/components/landing-page/js/bootstrap.min.js"></script>
  <script src="app/components/landing-page/js/owl.carousel.min.js"></script>
  <script src="app/components/landing-page/js/cbpAnimatedHeader.js"></script>
  <script src="app/components/landing-page/js/theme-scripts.js"></script>
  <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
  <script src="app/components/landing-page/js/ie10-viewport-bug-workaround.js"></script>
  <script type="text/javascript" src="app/components/landing-page/js/imageComparisonSlider.js"></script>
  <script>
    /*Execute a function that will execute an image compare function for each element with the img-comp-overlay class:*/
    initComparisons();
  </script>
<html>

as you see, there are several javascript files, and a funciton initComparisons() will be called.

If I only double click index.html, everything works fine. But I copy this html code in one component.html, that was not working. I can not see any animation.

I have googled some solutions, and I have change my angular.json file just like this:

 "scripts": [
              "src/app/components/landing-page/js/imageComparisonSlider.js",
              "src/app/components/landing-page/js/owl.carousel.min.js",
              "src/app/components/landing-page/js/cbpAnimatedHeader.js",
              "src/app/components/landing-page/js/theme-scripts.js"
            ]

and also import all js files in index.html in my angular web application

 <script src="app/components/landing-page/js/imageComparisonSlider.js"></script>
  <script src="app/components/landing-page/js/owl.carousel.min.js"></script>
  <script src="app/components/landing-page/js/theme-scripts.js"></script>
  <script src="app/components/landing-page/js/cbpAnimatedHeader.js"></script>

and in the component.ts, I also do this:

import initComparisons from './js/imageComparisonSlider.js';
ngOnInit() {
    this.isLoggedIn = this.authService.isLoggedIn;
    initComparisons();
  }

I added some code in stackblitz; https://stackblitz.com/edit/angular-qowfwy?file=angular.json

but it was not working.

can somebody help me and give me some suggestion.

Best Regards,

Leo

如果你想在你的角度项目中使用外部js,你必须在你的angular.json中导入“scripts”:[]区域,这将允许你带来js并在没有问题的情况下进行构建。

After putting the external scripts in angular.json (paths correct and everything), in component you should

declare const initComparisons;
// ...
ngOnInit() {
  initComparisons();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM