【问题标题】:Angular 8 - load scripts inside Angular component html divAngular 8 - 在 Angular 组件 html div 中加载脚本
【发布时间】:2020-04-06 04:47:22
【问题描述】:

我有以下两个脚本需要插入到我的 component.html 页面上的特定 div 中。我试过使用 dom sanitizer 没有运气。我还尝试按照此处的建议在 ngAfterViewInit 中创建脚本标签: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>

【问题讨论】:

    标签: angular


    【解决方案1】:

    感谢这篇帖子:http://blog.davidjs.com/2018/09/insert-script-tags-in-angular-components/

    就我而言,问题是第二个脚本需要在执行之前加载第一个脚本。

    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);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 2020-06-04
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 2020-05-20
      相关资源
      最近更新 更多