How to use jQuery with Angular

jQuery and Angular are two different technologies and have different paradigms; Angular embraces a declarative approach to DOM manipulation, while jQuery uses a more imperative style. Mixing these paradigms can lead to confusion and harder-to-maintain code.

Some third-party libraries still rely on jQuery. In such cases, we can use jQuery to integrate these libraries into our Angular application.

STEP 1 – First things first

// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install --save @types/jquery

STEP 2 – IMPORT

// Now, within any of the app files (ES2015 style)
import * as $ from 'jquery';
//
$('#elemId').width();

// OR

// CommonJS style - working with "require"
import $ = require('jquery')
//
$('#elemId').width();

#UPDATE – Sep - 2024

Lately, I’m writing code with ES6 instead of typescript and am able to import without * as $ in the import statement. This is what it looks like now:

import $ from 'jquery';
//
$('#elemId').width();

Reference

https://stackoverflow.com/questions/30623825/how-to-use-jquery-with-angular

https://dkreider.medium.com/how-to-use-jquery-with-angular-111fbe6b406f

FavoriteLoadingAdd to favorites

RECENT POSTS


Categories



Tags

ADO ai angular asian asp.net asp.net core azure ACA azure administration Azure Cloud Architect Azure Key Vault Azure Storage Blazor WebAssembly BLOB bootstrap c# containers css datatables design pattern docker excel framework Git HTML JavaScript jQuery json knockout lab LINQ linux power bi powershell REST API smart home SQL Agent SQL server SSIS SSL SVG Icon typescript visual studio Web API window os wordpress


ARCHIVE


DISCLAIMER