0

I have the below two scripts which need to be inserted into a specific div on my component.html page. I've tried using dom sanitizer with no luck. I've also tried creating the script tags in ngAfterViewInit as suggested here: angular2: including thirdparty js scripts in component.

<div id="uniqueId">
    <script src='https://script.js' type='text/javascript'></script>

    <script type='text/javascript'>
      initializeFunction('123456789');
    </script>

</div>
dc922
  • 629
  • 3
  • 14
  • 27

1 Answers1

1

Managed to get it working thanks to this post: http://blog.davidjs.com/2018/09/insert-script-tags-in-angular-components/

In my case the issue was that the second script needed the first one to be loaded before executing.

constructor(
    private renderer: Renderer2,
    @Inject(DOCUMENT) private _document
  ) {}


 ngAfterViewInit(){
    var s = this.renderer.createElement("script");
    s.onload = this.loadNextScript.bind(this);
    s.type = "text/javascript";
    s.src = "https://script.js";

    this.renderer.appendChild(this._document.body, s);
  }

  loadNextScript() {
    const s = this.renderer.createElement('script');
    s.text = `
    initializeFunction('1234566');
 `
    this.renderer.appendChild(this._document.body, s);
 }
dc922
  • 629
  • 3
  • 14
  • 27