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

I studied this topic a bit and learned about the library typings that you need to use for typescript. What I struggled to find are examples of using, say, for jquery inside an angular 2 application.

Here are a few questions:

1) Where would I write my jQuery code, is it inside the class or inside the constructor of this class?

2) Do I need to use document.ready at any time to port jQuery code? those. if we write code inside the constructor, does it fire after this event?

A few use cases, 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(); } } 
+7
javascript jquery angularjs angular typescript
source share
2 answers

Ideally, you should wait until the component content has been initialized to make the DOM available on which you want to apply jQuery . For this you need to use AfterViewInit , which is one of the angular2 hook of the life cycle .

You need to implement AfterViewInit in the class and write the add ngAfterViewInit method to receive a notification when the contents of the component are 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(); } } 
+10
source share

I am going to start by answering your second question. Yes, you should use document.ready because its intention is to wait for the DOM to load. If it is not loaded, your jQuery code will not work.

Now, to answer your first question, after loading, it doesn't matter where you call jQuery.

See this .

0
source share

All Articles