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