Because I want to incorporate Drag and Drop functionality in my app, I decided to import jQuery UI to my Angular 2 project.
First I started by importing jQuery itself by doing the following:
import { ElementRef } from '@angular/core';
declare var jQuery:any;
ngOnInit() {
jQuery(this._elRef.nativeElement).find('ul.tabs').tabs();
}
This works perfectly for initializing stuff. But when I try do to the .draggable()
function I get the following error:
jQuery(...).draggable is not a function
How can I make this work? I read a lot of approaches but all of them used system-js which in the current version on Angular-cli I do not use. I know that using jQuery in Angular 2 app is not really the best approach, but I just need a grid in which users can Drop draggable widgets.
If you have any suggestions, that will be perfect! Thanks!
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.
The jQuery project is actively maintained and widely implemented — it's used by 73% of 10 million most popular websites.
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.
I managed to make it work by doing the following steps:
In angular-cli.json I added my jquery and jquery-ui paths in the scripts object. Here is what they look:
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/jquery-ui/jquery-ui.js"
]
After I completed these steps, it worked like a charm. Hope that helps someone who had problems with it.
npm install jquery jquery-ui --save
npm install @types/jquery --save-dev
import * as $ from 'jquery';
import 'jquery-ui/ui/widgets/selectable.js';
usage:
ngAfterViewInit(): void {
($('.selectable') as any).selectable({..});
}
you may also want to import the stylesheet on style.scss if using sass
@import '../node_modules/jquery-ui/themes/base/selectable.css';
or
in .angular-cli.json
"styles": [
"../node_modules/jquery-ui/themes/base/selectable.css",
"./styles.scss"
],
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