Angular 1 and Angular 2 Integration

How to use jQuery with Angular 2?

Using jQuery with Angular 2, if we are using typescript (5, 6 and 7 versions) we should first add jQuery reference definition.

Stayed Informed  Angular 2 vs. Angular 1
Stayed Informed – Best Angular 2 Interview Q/A

We can see below line of code to install jQuery i.e.
tsd install jquery --save

OR
typings install dt~jquery --global –save 

And also we need to add the ts reference file.
/// <reference path="../typings/jquery/jquery.d.ts" />

Then make the necessary imports
import {bootstrap}    from 'angular2/platform/browser';
import {Component, ElementRef, AfterViewInit} from 'angular2/core';

Now, declare jQuery module and the declaring jQuery variable as JQueryStatic will give us a typed reference to jQuery.
1
2
3
4
declare module "jquery" {
    export = jQuery;
}
declare var jQuery: JQueryStatic;

In the last, write the class and components
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Component({
  selector: 'customer-app',
  templateUrl: 'index.html'
})
export class CustomerComponent implements AfterViewInit {
constructor(private el:ElementRef) {    }
  ngAfterViewInit() {   
         if(!CustomerComponent.chosenInitialized) {
           //TODO: your logic   jQuery(this.el.nativeElement)…
       }
  }
}

This live demo example,


For more detail go to links,

I hope you are enjoying with this post! Please share with you friends. Thank you so much!
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.