import {Component, ElementRef, OnInit} from 'angular2/core';
declare var jQuery:any;
@Component({
selector: 'jquery-integration',
templateUrl: './components/jquery-integration/jquery-integration.html'
})
export class JqueryIntegration implements OnInit {
elementRef: ElementRef;
constructor(elementRef: ElementRef) {
this.elementRef = elementRef;
}
ngOnInit() {
jQuery(this.elementRef.nativeElement).draggable({
containment:'#draggable-parent'
});
}
}
Can jQuery be used with TypeScript in Angular2 like the above? How do I use jQuery with JavaScript in Angular2?
Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation. Save this answer. Show activity on this post. That kind of lower-level hacking around the DOM, messing with the inline handlers, and cross-browser quirks thereof, is precisely the reason jQuery was born.
jQuery is a small yet feature-rich powerful javascript library that helps to manipulate the HTML DOM with less javascript code. We can use jQuery with Angular. There are some situations you come across while building Angular apps that it's absolutely necessary to use a library like jQuery to get something done.
It adds a lot to bundle size which is very bad for slow networks and CPUs (mobile!). Selectors and events are usually solved by libraries like React and Angular, so you don't need jQuery to help with browser compability and API differences.
In my opinion: if you do it right and if you keep it minimal, you should go with that.
Example:
@Directive({
selector: "[sm-dropdown]"
})
export class SMDropdown {
constructor(el: ElementRef) {
jQuery(el.nativeElement).dropdown();
}
}
Consider this Plunker:
https://plnkr.co/edit/MMNWGh?p=preview
Don't:
Once you have the JQuery typescript library installed, reference it in this way
///<reference path="../typings/jquery/jquery.d.ts" />
Then make the necessary imports
import {Component, AfterViewInit} from 'angular2/core';
Now write the class
@Component({
selector: 'my-app',
templateUrl: 'app/html/app.component.html'
})
export class AppComponent implements AfterViewInit {
ngAfterViewInit() {
// Your jQuery code goes here
$('#here').text("HALLO! ^_^");
}
}
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