In this post I will explain how to setup jQuery with Angular.
Step # 1 - Install jQuery using npm
Go to the root of the Angular project where angular.json file is placed, and run the following command to install jQuery dependency.
npm install --save jquery
Step # 2 - Add jQuery script reference in scripts array
You can now directly add jQuery script reference in index.html file, but a better approach would be to add the relative path in the scripts array in angular.json file.
"scripts": [ "node_modules/jquery/dist/jquery.min.js" ]
Step # 3 - Use jQuery in component
We need to declare the variable($) for jQuery as following.
declare var $: any;
Here we have defined $ variable with data type any to satisfy TypeScript compiler.
We have setup jQuery. Now we can write the jQuery code inside ngOnInit event of the component.
Here is sample code for AppComponent with jQuery variavble($) declarartion and its use in ngOnInit function.
import { Component, OnInit } from '@angular/core';
declare var $: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'jQuery with Angular';
public ngOnInit()
{
$(document).ready(() => {
$('#myDiv').html('Hello world from jQuery');
});
}
}
Where myDiv is the id of any empty div placed inside app.component.html template.
That's all set. Now when you run the component you should be able to see the jQuery message inside the target div.
I hope this helps some of you who may be looking to setup jQuery in Angular component.
ReplyDeleteWonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!
Hire Angularjs Coders in India