相当于$ document.ready()的Angular2 [英] Angular2 equivalent of $document.ready()

查看:85
本文介绍了相当于$ document.ready()的Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这是一个简单的问题.

Simple question, I hope.

我想在触发与$ document.ready()等效的Angular2时运行脚本.实现此目标的最佳方法是什么?

I want to run a script when the Angular2 equivalent of $document.ready() is fired. What is the best way to achieve this?

我尝试将脚本放在index.html的末尾,但是据我发现,这是行不通的!我认为它必须包含某种组件声明?

I've tried putting the script at the end of index.html, but as I found out, this doesn't work! I take it that it has to go in some kind of component declaration?

是否可以从.js文件运行脚本?

Is it possible to run load the script from a .js file?

编辑-代码:

我在我的应用程序中注入了以下js和css插件(来自铸造HTML主题).

I've got the following js and css plugins injected into my application (from the 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

As noted, the scripts.js 'instantiates' the whole thing, and thus is needed to be run after Angular is ready. 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
    }

推荐答案

您可以在Angular根组件的ngOnInit()中自己触发一个事件,然后在Angular之外侦听此事件.

You can fire an event yourself in ngOnInit() of your Angular root component and then listen for this event outside of Angular.

这是Dart代码(我不知道TypeScript),但翻译起来应该不难

This is Dart code (I don't know TypeScript) but should't be to hard to translate

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

这篇关于相当于$ document.ready()的Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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