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

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.