Using jQuery with Angular

- JavaScript Developer and Blogger
Published: Tue Sep 22 2015

In the following post I will describe how to integrate jQuery code with Angular.

Widespread use of jQuery is generally not a good idea in the context of Angular since it kind of goes against the spirit of Angular and other MVC frameworks. The biggest problem with jQuery is that it imposes a tight relationship between DOM and JavaScript – mainly because of selectors that assume a fixed DOM structure. I explain that some more here if you are interested.

That said, there are still a few acceptable uses cases for jQuery in Angular. One such example is jQuery plugins. In this post I will show you how to integrate the popular jquery-ui-draggable component with an Angular component. I will be applying the plugin to a component, which will let us drag the component around – inside the specified containment area.

While I recommend using this technique sparingly, Angular allows you to reach into the DOM and get access to the physical DOM element representing the component. This can be done by importing elementRef and injecting it into the constructor of the component.

The code below shows how to access the native element and wire it up to the draggable plugin.

import {Component, ElementRef, OnInit} from '@angular/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'}); } }

As you can tell, I am applying the plugin in the ngOnInit function in the component.

Given the easy access to the DOM via elementRef, it's fairly easy to apply the plugin. However, as I recommended above – only access the DOM directly when you absolutely have to. Generally it's much better to update the DOM via models and declarative bindings.

As always I have added this example to my live demo. The code is also on Github.

I invite you to follow me on twitter