Angular is a powerful JavaScript framework that is mostly used for building modern web applications. On the other hand, jQuery is a popular library used to handle DOM manipulations, animations and AJAX requests. Although Angular has its own way of handling these tasks, in some cases you might still want to use jQuery alongside Angular. In this blog post, we will explore how to run jQuery in Angular.
Step 1: Install jQuery
First of all, you need to install jQuery in your Angular project. You can do this by running the following command in your project’s root directory:
npm install jquery –save
This command will download the jQuery package and add it to your project’s dependencies.
Step 2: Add jQuery to Angular.json
Next, you need to add jQuery to your angular.json file so it can be included in your project’s build. Open the angular.json file and locate the scripts array inside the build section. Add the path to the jQuery file as shown below:
{ ... "build": { ... "options": { ... "scripts": [ "node_modules/jquery/dist/jquery.min.js" ], ... }, }, ... }
Save the angular.json file and restart your Angular development server if it’s running.
Step 3: Import jQuery in Your Component
Now that jQuery is installed and added to your project’s build, you can start using it in your components. To do this, you need to import the jQuery library first. Open the component where you want to use jQuery and add the following import statement at the top:
import * as $ from ‘jquery’;
This will import jQuery and make the $ variable available for use in your component.
Step 4: Use jQuery in Your Component
Now that jQuery is imported, you can use it in your component just like you would in any other JavaScript file. Here’s an example of how to use jQuery to toggle the visibility of an element when a button is clicked:
import { Component, OnInit } from '@angular/core'; import * as $ from 'jquery'; @Component({ selector: 'app-example', template: ``, styles: [] }) export class ExampleComponent implements OnInit { constructor() { } ngOnInit(): void { } toggleVisibility(): void { $('.hidden-element').toggle(); } }
In this example, we have a button with a (click) event that calls the toggleVisibility() method. Inside this method, we use jQuery’s toggle() function to show or hide the element with the .hidden-element class.
In Conclusion
Although Angular has its own tools and techniques for handling DOM manipulations, animations, and AJAX requests, there might be times when you want to use jQuery in your Angular project. This blog post has shown you how to run jQuery in Angular, by installing the jQuery package, adding it to your project’s build, importing it into your component, and using it in your component’s logic. Keep in mind that Angular is a powerful framework that provides many built-in features, so use jQuery only when it’s necessary or more efficient for your specific use case.