【问题标题】:How to include the External script only to the component?如何仅将外部脚本包含到组件中?
【发布时间】:2019-02-01 02:05:18
【问题描述】:

我的 Angular 应用程序有 form 组件,它依赖于外部脚本才能正常工作,

我知道要在 Angular 中包含外部脚本,我们可以执行以下操作之一:-

  1. angular.json 文件中创建条目
  2. index.html 中包含脚本
  3. component.html文件中包含脚本文件
  4. component.ts文件中导入脚本

以上方法都是全局包含脚本,在组件没有加载的情况下不起作用。

我希望附加到组件的脚本在每次加载/路由时运行。 所有 CSS 工作正常。

有没有办法让外部脚本成为组件的本地脚本并在每次加载时重新运行脚本?

【问题讨论】:

标签: angular typescript


【解决方案1】:

听起来像是dynamic import expressions 的案例。它们看起来像这样(引用文章):

import("./widget").then(widget => {
    widget.render(container);
});

renderWidget();

【讨论】:

    【解决方案2】:

    样本创建于 https://stackblitz.com/edit/angular-hadyfy 概述了如何仅将脚本执行包含到所需的组件(示例中的 c1 组件)中。

    如果这能解决您的问题,请告诉我。

    基本上这里的想法是回到将脚本元素子元素加载到文档 ==> 头元素的基础知识。

        ngAfterViewInit() {
    let url = "assets/c1.js";  //external script url
    let head = document.getElementsByTagName("head")[0];
    let scrs = head.getElementsByTagName("script");
    for(let i=0;i<scrs.length; i++){     
      let scr = scrs[i];
    
      if(scr.outerHTML.indexOf(url) >0){
        head.removeChild(scr);
      }
    }
        let script = document.createElement("script");
        script.src = url;
        script.type ="text/javascript";
        script.async = true;
        script.defer = true;
        head.appendChild(script);
    

    }

    【讨论】:

      【解决方案3】:

      您可以尝试 ngZone 并在 Angular 之外运行您的脚本

      【讨论】:

        【解决方案4】:

        尝试查看that,那里的人描述了如何动态下载模块(js 文件)并使用它,因此您可以从组件中的ngOnInitngAfterViewInit 钩子中执行相同操作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-15
          • 2018-03-29
          • 2019-07-30
          • 2019-04-12
          • 2019-02-11
          • 2023-02-02
          • 2021-05-14
          相关资源
          最近更新 更多