Can anyone tell me, how to use jQuery with Angular?
class MyComponent {
constructor() {
// how to query the DOM element from here?
}
}
I'm aware there are workarounds like manipulating the class or id of the DOM element upfront, but I'm hoping for a cleaner way of doing it.
Yet, if you load jQuery before angular, then angular will use jQuery. Most of the time, you do not need to use jQuery. Even so much that, for beginners, it is advised to leave out jQuery completely as there would be a tendency to use jQuery when there is an easy / angular way.
In the above code, we first import jquery to use its component. We then need to implement ngOnInit Lifecycle Hook which can be imported from Angular Core. We can write jQuery code inside the method ngOnInit, To add the action to the button we created in app. component.
JQuery is one of the most popular JavaScript libraries which exposes a lot of usable APIs for JavaScript developers. It's an integration with Typescript that may do wonders for you.
Yes. Angular does use . ts files by default. But if you write simple javascript code in them it will still work.
Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.
tsd install jquery --save
or
typings install dt~jquery --global --save
TypescriptDefinitions are not required since you could just use any
as the type for $
or jQuery
In your angular component you should reference a DOM element from the template using @ViewChild()
After the view has been initialized you can use the nativeElement
property of this object and pass to jQuery.
Declaring $
(or jQuery
) as JQueryStatic will give you a typed reference to jQuery.
import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;
@Component({
selector: 'ng-chosen',
template: `<select #selectElem>
<option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue">{{item}} option</option>
</select>
<h4> {{selectedValue}}</h4>`
})
export class NgChosenComponent implements AfterViewInit {
@ViewChild('selectElem') el:ElementRef;
items = ['First', 'Second', 'Third'];
selectedValue = 'Second';
ngAfterViewInit() {
$(this.el.nativeElement)
.chosen()
.on('change', (e, args) => {
this.selectedValue = args.selected;
});
}
}
bootstrap(NgChosenComponent);
This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview
tslint will complain about chosen
not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file
interface JQuery {
chosen(options?:any):JQuery;
}
This is what worked for me.
// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery
// 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();
Feb - 2017
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();
Good Luck.
Why is everyone making it a rocket science?
For anyone else who needs to do some basic stuff on static elements, for example, body
tag, just do this:
script
tag with the path to your jquery lib, doesn't matter where (this way you can also use IE conditional tags to load lower version of jquery for IE9 and less).export component
block have a function that calls your code: $("body").addClass("done");
Normaly this causes declaration error, so just after all imports in this .ts file, add declare var $:any;
and you are good to go!If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With