Using jQuery with Angular2

I know the idea of using jQuery with Angular2 may seen a little bit weird for lots of you, as we all know, Angular2 is responsible for managing everything related to our view components and DOM elements, it doesn’t sound like a good idea to use another framework to do a job Angular can easily do.

That being said, why would someone want to integrate jQuery with Angular2?

Well, there are some cases we still have to use jQuery, like for example, reusing some jQuery code or components when it’s not feasible to rewrite everything in Angular2, that’s probably the reason why you’re reading this tutorial.

Now let’s see how we can do this, it’s actually really simple, basically all you have to do is to add the jQuery script to your index.html and declare jQuery on your component, here is an example:

import {Component} from 'angular2/core';
 
declare var jQuery:any;
 
@Component({
    selector: 'my-app',
    template: `<button onclick="console.log('It Worked!!')">
                    jQuery Integration Test
               </button>
              `
})
 
export class AppComponent { 
 
    ngAfterViewInit() {
        jQuery('button').click();
    }
}

When you run your application you’ll see the text ‘It Worked!!’ on your console. That’s it!! This was a very short tutorial, but I hope it was helpful for you, just leave a comment if you have any doubts.