How to use jQuery with Angular?
How do you add jQuery to your Angular application?
The complete guide on adding jQuery to your Angular project - with code examples and explanations
Really? Before adding jQuery to your Angular project I recommend that you read this simple article to help you decide if using jQuery and Angular together is a good idea or not. This is a decision with long term consequences so it's worth thinking twice before making the jump.
How do you add the jQuery library to your Angular project?
And do it in 5 quick minutes?
In this guide I'll show you two different ways that you can use to install jQuery and use it in your Angular project.
1. The quick-n-dirty approach.
- Open the
index.html
file and add a script tag before the closing body tag like so.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Application</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
<app-root></app-root>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
</html>
- In your component's Typescript file declare a variable called jQuery. Here's how it looks.
declare var jQuery: any;
See full example below.
import { Component, OnInit } from "@angular/core";
import { Title } from "@angular/platform-browser";
declare var jQuery: any;
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
jQuery("#myselector").style="display: none;";
}
}
- Once your jQuery variable is declared you can use it anywhere in your components logic to manipulate the DOM, etc...
So what did we just do?
We added the jQuery script to our index.html file to make sure that it loads with the rest of our app. This gives us access to a variable called jQuery
but to use it we had to declare it at the top of our component's logic file as a type of any
that way Typescript wouldn't throw compile errors.
2. The clean and elegant approach.
- Run
npm install --save-dev @types/jquery
- Run
npm install --save jquery
- In your component file import jQuery where ever you want to use it like this.
import * as $ from 'jquery';
See full example below.
import { Component, OnInit } from "@angular/core";
import { Title } from "@angular/platform-browser";
import * as $ from 'jquery';
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
$("#myselector").style="display: none;";
}
}
3. Conclusion
So there it is - two different ways that you can add jQuery to your Angular project in less then 5 minutes.
Questions? Comments? Don't hesitate to poke me.
Angular Consultant