Javascript Angular2 JQuery,如何制作document.ready函数

Javascript Angular2 JQuery,如何制作document.ready函数,javascript,jquery,angular,Javascript,Jquery,Angular,我可以使用一些帮助来让JQuery函数在没有任何按钮点击的情况下运行。现在,它只在我有一个按钮可以点击时工作,因此JQuery将启动 代码 declare var jQuery: any; @Component({ selector: 'home-component', providers: [], moduleId: module.id, encapsulation: ViewEncapsulation.None, templateUrl: 'home.component.html', st

我可以使用一些帮助来让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();
        });
    }

}
此代码是组件内部的ofc。它找到该按钮,然后单击,它将运行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();
    });
}

希望有人能提供帮助。

我猜在
ngOnInit
上,id为
#owl example
的元素还不存在,因为它与调用
ngOnInit
的位置在同一个组件中。您必须使用
ngAfterViewInit
功能:

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

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

您可以在
ngAfterViewInit
hook中编写此代码

ngAfterViewInit(){    
  jQuery('#owl-example').owlCarousel();
}
我做到了,而且成功了

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() {


  }

}

jQuery('#owl示例').owlCarousel()你永远不应该做这样的事情。为什么我不应该做呢?因为你硬编码的CSS选择器,不灵活。你是说Id?。。也许我应该为所有的旋转木马创建一个类或其他东西:)?不,你根本不需要使用CSS选择器。这与在Angular1中的控制器中操作DOM是相同的反模式。现在您的组件代码被耦合到HTML,这是不好的。。我不知道你能做到。。很简单,谢谢你的快速帮助。