python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions