Angular 2 with JQuery – Part 1

I’ve seen people saying that there are problems with angular and jquery working together. To me, it’s not a single problem. Since angular uses/prefers typescript by default, it’s kind of combination of JQuery + Typescript + Angular. So, I decided to write about the problems people generally face during the development in a series of blog posts. This is the Part 1 of the series and meant for the beginners.

As a note, when I say Angular, it means Angualr 2.x and above (including Angular 4).

In  general, it’s not recommended to use more than one way to access/manipulate the DOM. Angular already does a nice job when it comes to DOM manipulation. You should be using Angular if you’re starting a new project.

But for the exising projects which uses JQuery extensively, you don’t have an option.

You may want to migrate to Angular, but it’s possible at once. You have to do it iteratively. So for the time being, you might want to use both angular and jquery at the same time.

Let’s start with a simple component.

import { Component, OnInit } from "@angular/core";

@Component({
  selector: 'app-root',
  template: `Click Me!`
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
  }
}

This is a plain angular component which simply shows a button called ‘Click Me’. If you click that button in browser, it’ll display you an alert message. Let’s add jquery on top of this and will make it more interesting.

npm install --save jquery

Here, I just installed jquery node module into project and saved it in package.json file.

If you’re using angular-cli for bootstrapping the project, then you need to tell the webpack (default build tool in angular-cli) to include the jquery during the build, so that it’ll be availble for your browser at runtime.

To do that, just replace the existing empty scripts block with this lines in your .angular-cli.json file.

"scripts": [
  "../node_modules/jquery/dist/jquery.min.js"
],

Now the setup is over!… We can start using it right away.

import { Component, OnInit } from "@angular/core";

declare var jQuery: any;

@Component({
  selector: 'app-root',
  template: `Click Me!`
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    jQuery('button').click();
  }
}

Here, I declared a type called jquery so that typescript compiler will not complain me about its usage. Since it’s declared as any, you can call any method on it. But in runtime (i.e, inside your browser), jquery variable will be interpretted as the actual jquery. So, it’ll work in the runtime.

If you run the above example, you’ll see an alert message when loading the page. That means, jquery is working with angular and typescript.

I won’t recommend to include this kind of logic in the ngOnInit() method in real applications.

PS: I used the following version of packages for this example. Angular 2.4.9, Typescript 2.0.0, Angular Cli 1.0.0-rc.1 & JQuery 3.1.1.

Advertisements