Introduction
In this article, we will be covering how to use JQuery in Angular. There are a few cases where we need to integrate jQuery in Angular for using a few features in our applications. Now we have seen that Javascript frameworks like AngularJs mess around jQuery. For briefing the functionalities of these frameworks, AngularJs is responsible for rendering and manipulating the DOM, and if we interfere with jQuery, we might get unwanted results.
For using the Angular application, we use the ng new command, and then we need to ‘cd’ for getting into the folder install jQuery via npm in the development environment.
Let’s consider a few orders you can follow for installation.
Installation
There are two ways you can install jQuery in AngularJs.
- npm method
- jQuery CDN
→ npm method: We can install jQuery using the NPM command. Before installing jQuery we have to create a new angular application. We can use this command for creating a new application,
ng new codingninjas |
We have created a new application codingninjas, the above command will take a few seconds to get executed, but will deliver a new application with all the desired files. Now we have created a new application but we are still not in the path of the application. For accessing the application and performing further installation for jQuery we will use the command given below:
cd codingninjas npm install jquery --save |
We have now successfully installed jQuery in our application. You can now easily use Jquery in the Angular application.
→ jQuery CDN: Using the website for jQuery, you can download the dependencies, you can download the CDN and use it. To use jQuery CDN you will need to have a script tag in your files, version 3.4.1 is used here,the code you can use is,
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-2z0P7MLoyxByUtvAk/xjkmindefS4auh4Pfzbm7y6g0=" crossorigin="anonymous"> </script> |
Example
In the given example we have used jQuery in Angular and created an application displaying a button with the animation.
HTML Code -
<!DOCTYPE html> <html> <head> <title>Jquery in Angular</title> </head> <body> <h1 style="color:blue"> CodingNinjas </h1> <h2>Jquery in Angular</h2> <button>Start Animation </button> <div style="border:1px solid; border-radius:3px; color:white; background:red; height:105px; width:260px; position:relative;"> jQuery in Angular </div> </body> </html> |
Angular.js code -
import { Component, OnInit} from '@angular/core'; import * as $ from 'jquery' export class AppComponent implements OnInit { ngOnInit(){ $(document).ready(function(){ $("button").click(function(){ var div=$("div"); div.animate({left:'100px'}, "slow"); div.animate({fontSize:'5em'}, "slow"); }); }); } |
OUTPUT
Refer to know about: jquery ajax