Angular2中如何使用JQuery的document.ready函数

3

我需要帮助使JQuery函数在没有按钮点击的情况下运行。目前只有在我有一个按钮可以点击时,JQuery才会触发。

代码

declare var jQuery: any;

@Component({
selector: 'home-component',
providers: [],
moduleId: module.id,
encapsulation: ViewEncapsulation.None,
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
directives: [BannerComponent],
})

export class HomeComponent implements OnInit {

    constructor(public productService: ProductService, private elref: ElementRef) {

    }

    ngOnInit(): any {
        console.log("jQuery here");
        jQuery(this.elref.nativeElement).find('button').on('click', function ()          {
            jQuery('#owl-example').owlCarousel();
        });
    }

}

这段代码是在组件内部。它找到按钮,当被点击时,将运行jQuery函数。

我的目标是让这一行更加易懂:

jQuery('#owl-example').owlCarousel();

在ngOnInit被调用时触发(不需要任何按钮点击)。为了做到这一点,我需要实现JQuery:

$(document).ready(function() { }

这里的问题是它不起作用 :) 我尝试过的代码如下:
ngOnInit(): any {
    console.log("jQuery here");
    jQuery(this.elref.nativeElement).ready(function() {
        jQuery('#owl-example').owlCarousel();
    });
}

希望有人能够帮忙。

这与IT技术无关。

1
jQuery('#owl-example').owlCarousel(); 你绝不能做这样的事情。 - dfsq
那我为什么不应该这样做呢? - Mikkel
1
因为你硬编码了CSS选择器,不够灵活。 - dfsq
你是指Id吗?也许我应该为所有的走马灯制作一个类或其他什么东西? - Mikkel
不,你永远不应该需要使用CSS选择器。这与在Angular1控制器中操作DOM一样是一种反模式。现在你的组件代码与HTML耦合在一起,这是不好的。 - dfsq
3个回答

8

我猜测在ngOnInit期间,具有#owl-example ID的元素还不存在,因为它与调用ngOnInit的组件位于同一位置。您需要使用ngAfterViewInit函数:

ngAfterViewInit(): void {
   jQuery('#owl-example').owlCarousel();
}

您可以确保组件中的任何元素存在于文档中。


可以工作了,我不知道你可以这样做,非常简单,感谢你的快速帮助。 - Mikkel

4

您可以在ngAfterViewInit钩子内编写此代码。

ngAfterViewInit(){    
  jQuery('#owl-example').owlCarousel();
}

3

我做到了,而且它有效!

import { Component, OnInit, AfterViewInit } from '@angular/core';

declare var jQuery: any;

@Component({
  selector: 'app-banners',
  templateUrl: './banners.component.html',
  styleUrls: ['./banners.component.css']
})
export class BannersComponent implements AfterViewInit {

  ngAfterViewInit(): void {
   jQuery('.slider').slider({full_width: true});
}


  constructor() { }

  ngOnInit() {


  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接