I have tried all the life cycle hooks but can't get to accomplish the needed result. The result that I need is triggering a function that initialize many jquery plugins used for different elements on a single page after every single one of these elements (components) is loaded.
So lets say that you have this structure.
Home Page Slider Widgets Product rotators ..etc
Every one of these elements has it's own component and all are children of the Home page parent component.
And what I need here is to know when all the children components and the parent component is loaded so I trigger one jquery function to initialize every plugin on the page.
You will want to use the "ngAfterViewInit" lifecycle hook, through importing AfterViewInit (https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview). You can use it as shown below:
Installation:
tsd install jquery --save
or
typings install dt~jquery --global --save
Utilization:
import { Component, AfterViewInit } from '@angular/core'; import * as $ from 'jquery'; ngAfterViewInit() { this.doJqueryLoad(); this.doClassicLoad(); $(this.el.nativeElement) .chosen() .on('change', (e, args) => { this.selectedValue = args.selected; }); } doClassicLoad() { // A $( document ).ready() block. $( document ).ready(function() { console.log( "Unnecessary..." ); }); } // You don't need to use document.ready... doJqueryLoad() { console.log("Can use jquery without doing document.ready") var testDivCount = $('#testDiv').length; console.log("TestDivCount: ", testDivCount); }
Here is a plunker for an example: http://plnkr.co/edit/KweZYO9hk9Dz8pqDK77F?p=info
The most effective way that I have found is to use setTimeout with time of 0 inside of the page/component constructor. This let's the jQuery run in the next execution cycle after Angular has finished loading all the child components.
export class HomePage { constructor() { setTimeout(() => { // run jQuery stuff here }, 0); } }
Putting the setTimeout inside of ngOnInit method has also worked for me.
export class HomePage { ngOnInit() { setTimeout(() => { // run jQuery stuff here }, 0); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With