1

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?

5
  • Hi @Henry Sachs Any html template references? Commented Sep 13, 2017 at 15:30
  • For what reason you asking? I got one button with a onclick method. Commented Sep 13, 2017 at 17:04
  • no reason i didn't :) !, i was just asking this : Hi Any html template references? Commented Sep 13, 2017 at 17:07
  • And I answered yes one button. Or what do you call html template references? Commented Sep 13, 2017 at 17:09
  • It was about a problem and understand a few more what you did, i have to go ;) cya Commented Sep 13, 2017 at 17:14

1 Answer 1

1

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();
        });
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

I don’t have the possibility to try this currently but will come back to this.
so this still doesnt work for me and i get the same errors that he cannot find the name logger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.