1

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>

1 Answer 1

3

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

Comments

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.