Robert
Robert

Reputation: 333

Angular with External JavaScript doesn't run after Component change

So I created a script.service.ts file that I inject my JavaScript files into different components when needed in my project. However I am still facing a issue I had before I created that when I simply just included the script links in the index.html file. That issue is that say you load up a page say called "localhost:4200/user and that uses a component that is using a external JavaScript file to activate the users web cam for example. Everything will work great however if you load up say "localhost:4200/login" and then click a button that routes you to "localhost:4200/user" the camera functionality will not work. I'm just using this functionality as a example of course.

But the main issue is if you load one component first then route to a component that has java script functionality from a external file that functionality will not work unless you start on that component. So how can I force angular to reload functionality for external JavaScript files on route change?

I am using the latest version of Angular. Thank you for the help in advance!

Upvotes: 4

Views: 3929

Answers (1)

Mohammed Rishad
Mohammed Rishad

Reputation: 335

Instead of loading scripts in angular-cli.json change app.component.ts to :

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) {

    }

    ngOnInit() {
        this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                if (document.getElementById('custom_js') !=null) {
                    document.getElementById('custom_js').remove();
                }
                const node = document.createElement('script');
                node.src = 'assets/js/custom_scripts.js';
                node.type = 'text/javascript';
                node.async = false;
                node.id = 'custom_js';
                node.charset = 'utf-8';
                document.getElementsByTagName('head')[0].appendChild(node);
            }
        });
    }
}

This will reinsert js file after every routing. No need to load the script in every component. This will do the magic!!!

Upvotes: 2

Related Questions