Mikkel Mikkel - 4 months ago 34
Javascript Question

Angular2 Jqeury, how to make the document.ready function

I could use some help in order to make the jquery function run without any button click. Right now it only works when I have a button to click on, so the jQuery will fire.

Code

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("Jqeuery here");
jQuery(this.elref.nativeElement).find('button').on('click', function () {
jQuery('#owl-example').owlCarousel();
});
}

}


This code is ofc inside a component. It finds the button, and on click, it will run the jQuery function.

What I want is to make this line:

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


Fire when the ngOnInit is called (without any button click). To do so I need to implement the Jquery:

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


The problem here is that it does not work :) What I have tried so far are this peace of code:

ngOnInit(): any {
console.log("Jqeuery here");
jQuery(this.elref.nativeElement).ready(function() {
jQuery('#owl-example').owlCarousel();
});
}


Hope someone can help.

Answer

I would guess that on ngOnInit the element with id #owl-example does not exists yet, because it is in the same component as where the ngOnInit gets called. You have to use the ngAfterViewInit function:

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

You can then be sure that any element in your component exists in the document.