Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jQuery in an Angular 8 app?

I have an application that utilizes SignalR to communicate with a desktop application. To utilize SignalR I need to use jQuery in my .ts file. However, it doesn't seem to work post migrating from Angular 7 to Angular 8.

I use declare var $: any; as I have in previous versions of Angular. Unfortunately, $ now prints blank to the console.

So, does Angular v8 no longer support using jQuery this way, or did something else break in the migration?

Update:

I have jQuery v3.3.1 loaded via npm.

This makes it global (in angular.json)

"scripts": [
         "./node_modules/jquery/dist/jquery.min.js",
         "./node_modules/signalr/jquery.signalR.js"
]
like image 463
Irrelevant_Coder Avatar asked Jul 08 '19 20:07

Irrelevant_Coder


People also ask

Is it possible to use jQuery in Angular?

jQuery is a small yet feature-rich powerful javascript library that helps to manipulate the HTML DOM with less javascript code. We can use jQuery with Angular. There are some situations you come across while building Angular apps that it's absolutely necessary to use a library like jQuery to get something done.

Why jQuery is not used in Angular?

It adds a lot to bundle size which is very bad for slow networks and CPUs (mobile!). Selectors and events are usually solved by libraries like React and Angular, so you don't need jQuery to help with browser compability and API differences.


2 Answers

More elegant way without using

declare var $: any;

First run

npm install jquery --save
npm install @types/jquery --save

Then in scripts section in architect => build of angular.json file add path for jquery lib

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

Then in your tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["jquery"] // add here
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}

So now you can use jquery anywhere in your project without using declare var $ : any for every file you need to use jquery

like image 66
Tony Ngo Avatar answered Sep 20 '22 19:09

Tony Ngo


Angular 8 works with JQuery.

 "dependencies": {
  ...
  "jquery": "^3.4.1",
  ...
}

in your angular.json file import the required file like this:

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

no ./ at the beginning, just node_modules/...

In your app.module verify it is working like this:

import { AppComponent } from './app.component';

declare var $: any;
console.log(`jQuery version: ${$.fn.jquery}`);

@NgModule({

In the developer tools console it should print this:

jQuery version: 3.4.1

like image 43
robert Avatar answered Sep 21 '22 19:09

robert