Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use libraries like jquery/jqueryui inside angular 2 component

I have researched this topic a bit and found out about typings for libraries that need to be used for typescript. What I struggled to find is examples of usage, lets say for jquery inside an angular 2 application.

here are some questions:

1) Where would one write his jQuery code, is it inside class or inside constructor of that class?

2) Do we need to use document.ready at any point to wrap jQuery code? i.e. if we write code inside constructor is it run after this event?

few examples of usage, is one of these correct?

example 1

export class MyApp {
   constructor() {
      $('.mydiv').hide();
   }
}

example 2

export class MyApp {
   constructor() {
   }

   $('.mydiv').hide();
}

example 3

export class MyApp {
   constructor() {
   }

   $( document ).ready(function() {
     $('.mydiv').hide();
   }
}
like image 913
Ilja Avatar asked Jan 28 '16 21:01

Ilja


1 Answers

Ideally you should wait till component content get initialized, in order to make the DOM available on which you wanted to apply jQuery. For that you need to use AfterViewInit which is one of hook of angular2 lifecycle.

You need to implement AfterViewInit on a class and write add ngAfterViewInit method to get notify whenever component content gets ready.

import { AfterViewInit } from 'angular2/core';

export class MyApp implements AfterViewInit {
   constructor() {
   }

   ngAfterViewInit(){
       //here you will have code where component content is ready.
       $('.mydiv').hide();
   } 
}
like image 78
Pankaj Parkar Avatar answered Oct 07 '22 01:10

Pankaj Parkar