How to use jQuery in Angular 2

First install jQuery with NPM: npm install --save jquery

Update scripts key in your angular-cli.json to include jQuery

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

You should stop angular-cli and rerun it using ng serve.

Now jQuery is available globally in the application. Whenever you need to use just declare $ or jQuery at the top like so:

import { Component, OnInit } from '@angular/core';  
// import line is this one
declare var $:any;
//declare var jQuery: any;

export default class Random implements OnInit {  
  ngOnInit() {
    // $ will be availble
    console.log($);
  }
}

 

Advertisements