![](/img/trans.png)
[英]jQuery - How to create a new function to simulate document.ready on ajaxComplete?
[英]Angular2 JQuery, how to make the document.ready function
我可以使用一些幫助,以便在沒有任何按鈕點擊的情況下運行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();
});
}
希望有人能提供幫助。
我猜想,在ngOnInit
與ID的元素#owl-example
不存在的,但因為它是在相同的組件,其中ngOnInit
被調用。 你必須使用ngAfterViewInit
函數:
ngAfterViewInit(): void {
jQuery('#owl-example').owlCarousel();
}
然后,您可以確保組件中的任何元素都存在於文檔中。
您可以在ngAfterViewInit
鈎子中編寫此代碼
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() {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.