Using jQuery from Angular 2

At times you may need to use jQuery from Angular 2. Here are a couple of ways to do just that.

Method 1: The quick way

The quick way to use jQuery from Angular 2 is to simply:

1. Add a jQuery script tag

In your index.html add a script tag with the path to the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

2. Declare $ as any

Where you need to use jQuery, simply declare ‘$’ of type any after the import statements.

import { Component, Input, OnInit, AfterViewChecked } from '@angular/core';
...
declare var $: any;

3. Call jQuery

Call jQuery ($) as needed, but from within the appropriate Angular lifecycle hook, ie ngAfterViewInit or ngAfterViewChecked

ngAfterViewChecked() {
    let self=this;
    $("g.note").off().on('click', function() { self.noteClicked(this.id); });

    ...
}

This is the approach I took for PianoPlay, however there is a better way.

Method 2: A better way (also quick)

Whilst the previous approach works, it doesn’t provide a very good developer experience. A better way involves installing jQuery via NPM and using the jQuery typescript declaration file.

1. Install jQuery using NPM

npm install --save jquery

2. Install the jQuery declaration file

npm install -D @types/jquery

3. Import jQuery

import * as $ from 'jquery';

This provides a typed reference to jQuery, which means in Visual Studio Code, you go from this:

Method 1

To this..

Method 2

Much better IMHO :)