Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery UI with Angular 2

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!

like image 434
Georgi Arnaudov Avatar asked Jan 25 '17 20:01

Georgi Arnaudov


People also ask

Can I use jQuery and Angular together?

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.

Is jQuery UI still used?

The jQuery project is actively maintained and widely implemented — it's used by 73% of 10 million most popular websites.

Why jQuery is not used in Angular?

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.


2 Answers

I managed to make it work by doing the following steps:

  1. npm uninstall jquery jquery-ui
  2. npm cache clean
  3. npm install jquery jquery-ui
  4. 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.

like image 128
Georgi Arnaudov Avatar answered Oct 09 '22 03:10

Georgi Arnaudov


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"
],
like image 32
Ivan Carmenates García Avatar answered Oct 09 '22 01:10

Ivan Carmenates García