我希望是个简单的问题。
我希望在触发$document.ready()的Angular2等效项时运行脚本。实现这一目标的最佳方法是什么?
我试着将脚本放在index.html
的末尾,但我发现这不起作用!我认为它必须放在某种组件声明中?
是否可以从.js
文件中运行加载脚本?
编辑-代码:
我已经将以下js和css插件注入到我的应用程序中(从Foundry html theme)。
<link href="css/themify-icons.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
...
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/flexslider.min.js"></script>
...
<script src="js/scripts.js"></script> //This initiates all the plugins
正如前面提到的,scripts.js“实例化”了整个过程,因此需要在Angular准备好之后运行。script.js
让它工作了:
import {Component, AfterViewInit} from 'angular2/core';
@Component({
selector: 'home',
templateUrl: './components/home/home.html'
})
export class HomeCmp implements AfterViewInit {
ngAfterViewInit() {
//Copy in all the js code from the script.js. Typescript will complain but it works just fine
}
发布于 2015-12-31 21:26:34
您可以自己在Angular根组件的ngOnInit()
中激发一个事件,然后在Angular外部侦听此事件。
这是Dart代码(我不知道TypeScript),但应该不难翻译
@Component(selector: 'app-element')
@View(
templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
ElementRef elementRef;
AppElement(this.elementRef);
void ngOnInit() {
DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
}
}
发布于 2016-05-25 22:02:08
从Chris那里复制答案:
让它工作了:
import {AfterViewInit} from 'angular2/core';
export class HomeCmp implements AfterViewInit {
ngAfterViewInit() {
//Copy in all the js code from the script.js. Typescript will complain but it works just fine
}
发布于 2016-06-16 03:41:55
我采用了这个解决方案,因此除了jQuery $.getScript函数之外,我不必在组件中包含我的自定义js代码。
注意:依赖于jQuery。因此,您将需要jQuery和jQuery类型。
我发现这是绕过自定义或供应商js文件的一个好方法,这样当你启动你的应用程序时,TypeScript就不会对你尖叫。
import { Component,AfterViewInit} from '@angular/core'
@Component({
selector: 'ssContent',
templateUrl: 'app/content/content.html',
})
export class ContentComponent implements AfterViewInit {
ngAfterViewInit(){
$.getScript('../js/myjsfile.js');
}
}
更新实际上在我的场景中,OnInit生命周期事件工作得更好,因为它阻止了在加载视图之后加载脚本( ngAfterViewInit就是这种情况),并且导致视图在脚本加载之前显示不正确的元素位置。
ngOnInit() {
$.getScript('../js/mimity.js');
}
https://stackoverflow.com/questions/34547127
复制相似问题