问题描述
在我的 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文件.
建议?
推荐答案
Use the AfterContentChecked
LifeCycle.
-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文件脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!