How to call external javascript function in angular 5?

前端 未结 4 1543

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

index.html (body section)


  

        
相关标签:
4条回答
  • 2020-12-17 05:33

    You can call these methods by window object-

    document.addEventListener("DOMContentLoaded", function (event) {
          window['navbarToggleSidebar']();
          window['navActivePage']();
     });
    
    0 讨论(0)
  • 2020-12-17 05:49

    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.

    0 讨论(0)
  • 2020-12-17 05:51

    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

    0 讨论(0)
  • 2020-12-17 05:51

    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>
    
    0 讨论(0)
提交回复
热议问题