Angular:在加载组件视图后加载外部JS文件脚本 [英] Angular : load an extrenal JS file script after Component View loaded

查看:361
本文介绍了Angular:在加载组件视图后加载外部JS文件脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Anglar 5 应用中,我有一个js脚本文件,我想在加载组件视图后动态加载

Under my Anglar 5 app, I have a js script file which I want to load dynamically after the loading of my component view,

这是因为我的脚本与组件模板一起工作,并且需要加载视图才能运行

this is because my script acts with my component template, and need to have the view loaded to run

我已经尝试过了:

export class MyComponent implements AfterViewInit{
   title = 'app';
   ngAfterViewInit() {
     this.loadScript('http://www.some-library.com/library.js');
     // OR THIS
     this.loadScript('../assets/js/my-library.js');
   }
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}

但是它仍然在加载组件HTML文件之前先加载我的js. ,这导致我的脚本无法运行.

But it still loads my js before the loading of my component HTML file. , and this results on the non-running of my script.

(我在体内看到了它,但实际上它不起作用)

(i see it in the body but in reality, it's not working)

我的目的是在加载组件后加载我的js文件.

建议?

推荐答案

使用 AfterContentChecked生命周期.

Use the AfterContentChecked LifeCycle.

AfterContent挂钩 AfterContent挂钩类似于AfterView挂钩.关键区别在于子组件.

AfterContent hooks AfterContent hooks are similar to the AfterView hooks. The key difference is in the child component.

-AfterView挂钩涉及ViewChildren,这是其元素标签出现在组件模板中的子组件.

-The AfterView hooks concern ViewChildren, the child components whose element tags appear within the component's template.

-AfterContent挂钩与ContentChildren有关,ContentChildren是Angular投影到组件中的子组件.

-The AfterContent hooks concern ContentChildren, the child components that Angular projected into the component.

另一种方法:

我很久以前用以下方法解决了这个问题:

I solved this a long time ago with:

ngAfterViewInit() {
    setTimeout(() => {
        doSomething();
    }, 0);
}

这篇关于Angular:在加载组件视图后加载外部JS文件脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆