【问题标题】:How to call $( document ).ready() jQuery function with in ngAfterViewInit() on Component class using angular 2如何使用 Angular 2 在组件类的 ngAfterViewInit() 中调用 $( document ).ready() jQuery 函数
【发布时间】:2018-05-24 16:04:42
【问题描述】:

代码是

constructor(private el: ElementRef) { }

ngAfterViewInit() {

    this.loadScript('app/homepage/template-scripts.js');       


}

【问题讨论】:

    标签: angular typescript angular2-directives angular-components


    【解决方案1】:

    Angular 让您通过生命周期事件避免这种 jquery 依赖:

    (按生命周期排序)

    -ngOnChanges -ngOnInit -ngDoCheck -ngAfterContentInit -ngAfterContentChecked -ngAfterViewInit -ngAfterViewChecked -ngOnDestroy

    如果你想使用 jquery 函数.ready,你应该在你的 Angular 项目中导入 jquery 作为依赖,然后在你的 .ts 文件中导入相关模块并在 ngAfterViewInit 中调用它:

    // In the console
    // First install jQuery
    npm install --save jquery
    // and jQuery Definition
    npm install -D @types/jquery
    
    -----
    
    import $ from 'jquery';
    //
    
    ngAfterViewInit() {
    // other stuffs
    
    if ($.ready()) {
        console.log('ready');
      }
    }

    我上面的代码有效。

    但我想向您解释这是不好的做法,因为您要将逻辑放入现有的角度生命周期逻辑中。

    https://angular.io/guide/lifecycle-hooks

    希望对你有所帮助

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      相关资源
      最近更新 更多