Ilja
Ilja

Reputation: 46479

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();
   }
}

Upvotes: 7

Views: 2009

Answers (2)

Kody
Kody

Reputation: 965

I'm going to start by answering your second question. Yes, you should use document.ready because its intention is to wait until the DOM is loaded. If it's not loaded, your jQuery code won't work.

Now to answer your first question, once loaded, it shouldn't matter where you call jQuery.

See this.

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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();
   } 
}

Upvotes: 10

Related Questions