Henry Sachs
Henry Sachs

Reputation: 302

Load Javascript Scripts dynamically in Angular 4

I want to Load a Script dynamic in Angular 4. The name for the Script itself will later be from an Ajax Call. Currently to load the JavaScript File i imported Jquery to my Angular Project. After that i use the GetScript Method and can load that file but if i want to invoke a function like this:

import { Component } from '@angular/core';
import * as jQuery from 'jquery';

declare var $:any;
declare var jquery:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  title = 'angular 4 with jquery';
  url = "currently hardcoded";

    getScript42(){
      $.getScript(this.url).done(function() {
      logger();
    });
    }
  }

I get the following error: Cannot find name 'logger'

But in my JavaScript File the function is defined:

$(document).ready(function(){

  function logger(){
  console.log("it worked");
  }
});

If i dont use a function for this it worked.

So now to my Problem do you guys know a way to load that File and invoke a specific function?

Upvotes: 1

Views: 946

Answers (1)

Aniruddha Das
Aniruddha Das

Reputation: 21688

In the angular life cycle AfterViewInit is called when the view is loaded, That means your html is dom ready and ready to accept any additional script tags.

so you can write these in your afterviewinit method by implementing the interface.

declare var $:any;
declare var jquery:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  title = 'angular 4 with jquery';
  url = "currently hardcoded";

      ngAfterViewInit(): void {
        $.getScript(this.url).done(function() {
          logger();
        });
    }
  }

Upvotes: 1

Related Questions