How to use JQuery in Angular?

Luka Onikadze
3 min readMay 15, 2020
Image by Momentmal from Pixabay

Using Angular in JQuery is not the best practice but if you want to, or have to, I’ll show how to do it in a few simple steps

Installation

First, install the JQuery library.

npm install jquery --save

We need to install JQuery definition file also, to get IntelliSense support

npm install @types/jquery --save-dev

Import into Application

As we know JQuery is one big javascript object. We cannot import it, like we commonly do inside Angular applications, for example like this:

import { Input} from "@angular/core"

Because of that, firstly, we have to load JQuery inside Angular application. Open angular.json file, and in scripts, array add the following value

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

By that way, JQuery is loaded exactly as if you had added it in a <script> tag inside index.html

Next, we have to import the library into the Angular application, otherwise, the compiler will think, that we are not using it and will not include it in a bundle file

Open main.ts file and insert

import "jquery";

Now JQuery is fully loaded inside our application.

You can type JQuery anywhere in your app, and you will see IntelliSense right away (remember not $, you should type “JQuery”)

How to properly use JQuery?

One thing to remember is that you have to wait until the view is loaded and then use JQuery, otherwise the element will not be in HTML yet

ngOnInit(){
//not here
}
ngAfterViewInit(){
//use here
JQuery("#myElement").hide();
}

The proper way to use it is to get a reference of an element, using the ViewChild decorator and use this element as Selector. I can show you by example

--

--