6

Sorry guys if this question is duplicate. I couldn't able to find any proper solution still on web so I am posting here.

I am creating a component in angular 2. I am having an external js file and loading it dynamically. In the external js file, I am having a function with parameter. How can I call that parameter inside the ngAfterViewInit. I am new to Angular 2, so don't know how to call the js function in Angular 2 typescript, I will post my code for your reference

app.component.ts

import { Component, OnInit, ElementRef,AfterViewInit  } from '@angular/core';
declare var $:any;
@Component({
  selector: 'app-root',
  template: '<div></div>'
})

export class AppComponent implements AfterViewInit {
 urlinput;  
  constructor(elRef: ElementRef){
    this.urlinput = elRef.nativeElement.getAttribute('urlinput');
    this.loadScript();
  }
     ngAfterViewInit() {
  // need to call the js function here 
  //tried like this initializeDataTable(this.urlinput) not worked
  }

loadScript() {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "app/Message.js";
    head.appendChild(script);
}  
}

Message.js (External Js File)

function initializeDataTable(dTableURL){
        $.ajax({
                "url": dTableURL,
                "success": function(json) {
                    var tableHeaders;
                    $.each(json.columns, function(i, val){
                      tableHeaders += "<th>" + val + "</th>";
                    });
                    $("#tableDiv").empty();
                    $("#tableDiv").append('<table id="displayTable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>');
                    $('#displayTable').dataTable(json);
                },
                    "dataType": "json"
         });
    }

index.html

  <app-root urlinput="app/array.txt">Loading...</app-root>

Please help me to resolve this issue.

1 Answer 1

2

That should create a message property on the window object. Since the window object is probably declared in some definition file, you could do this:

window['message']('Hello, world!')

Or set it to a variable and use it:

var message: any = window['message'];
message('Hello, world!');

Or the property typescript way, declare the function, this can go in any file named .d.ts in your source folder:

declare function message(msg: string) : void;

See this question too.

The problem with loading the script dynamically is that you can't be sure that the script is loaded when your code executes. You probably should create a service with a message(msg: string) method. The constructor for the service can create the script tag (and check if one already exists if not a singleton), and queue up messages if you want to process them after the script loads. Detecting the loading of a script doesn't have full cross browser support, so you could do something like google analytics does and set some global window property that your external script will call at the end to process any pending messages:

In service:

constructor() {
  if (!window['message']) {
    window['message'] = function(msg) {
      window['messagequeue'] = window['messagequeue'] || [];
      window['messagequeue'].push(msg);
    }
  }
  // add script tag to load script
}

message(msg) {
  window['message'](msg);
}

In your script:

function message(msg) {
  console.log(msg)
  //logics goes here
}

// process messages queued before script loaded
if (window['messagequeue']) {
  window['messagequeue'].forEach(msg => message(msg));
}
Sign up to request clarification or add additional context in comments.

4 Comments

can you please correct my code for property typescript way , I can't able to get you
Sorry Not Working
the question link which you gave is not relevant, it is to import function from two .ts file not the import from .js to .ts file hope you understand
It actually works the same. The typescript compiles to javascript, all the declare does is make it so the typescript compiler knows that function exists in the javascript engine somewhere. It could be in another typescript file (that is compiled to javascript), in a javascript file like in your case, or provided by the browser. It just lets the typescript compiler know that the function exists out there somewhere.

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.