How to load external script after Angular 2 loads

1.1k Views Asked by At

I have dynamic navigation bar which fetch data from API.

The problem is the list items in the navigation bar does not toggling consistently. It works sometimes and doesn't most of the time.

There are no script error in the console window, its clean.

The script for the navigation panel toggle is from the Metronic template itself in the file called layout.js

I am suspecting its because the layout.js loads before the angular renders in DOM sometimes. It that case the toggle doesn't work properly.

Any Suggestions please !

enter image description here

<!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>    
    <script src="/node_modules/zone.js/dist/zone.js"></script>    
    <script src="/node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="/systemjs.config.js"></script>
    <script>
        System.import('app').catch(function (err) { console.error(err); });
    </script>

 <!-- BEGIN THEME LAYOUT SCRIPTS -->

    <script src="~/assets/layouts/layout/scripts/demo.min.js" defer type="text/javascript"></script>
    <script src="~/assets/layouts/global/scripts/quick-sidebar.min.js" defer type="text/javascript"></script>
    <script src="~/assets/layouts/global/scripts/quick-nav.min.js" defer type="text/javascript"></script>
    @*<script src="~/Scripts/jquery-1.10.2.min.js"></script>*@
    <script src="~/assets/global/plugins/bootstrap/js/bootstrap.min.js"></script>
    <script src="~/assets/layouts/layout/scripts/layout.js" defer></script>
    <!-- END THEME LAYOUT SCRIPTS -->
1

There are 1 best solutions below

0
On

Try this:

Import the AfterViewInit from @angular/Core and implement it's function.

Make sure your layout.js is referenced in the scripts for your app in the angular-cli.json.

In your component.ts import your layout.js like this:

import {layout} from 'file/location/layout.js';

Edit your layout.js file to have its current code wrapped with this:

var extJs = (function() {
    return{
    getExtJs: function() {
        //js code goes here
    }
}

Back in your component declare a variable that refers to the one in layout.js:

declare var extJs: any;

Then call the layout.js function when the view has finished loading:

ngAfterViewInit(): void {
    extJs.getExtJs();
  }