Waog Waog - 2 years ago 16063
Javascript Question

How to use jQuery with Angular2?

can anyone tell me, how to use jQuery with Angular2?

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.

Answer Source

Using jQuery from Angular2 is a breeze compared to ng1. If you are using typescript you should first reference jQuery typescript definition

tsd install jquery --save

And in your ts file:

/// <reference path="typings/jquery/jquery.d.ts" />

tslint will give you an error since $ conflicts with protractor Subsequent variable declarations must have the same type. Variable '$' must be of type 'cssSelectorHelper', but here has type 'JQueryStatic'

Modify jquer.d.ts and change

declare module "jquery" {
    export = $;
}
declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;

To:

declare module "jquery" {
    export = jQuery;
}
declare var jQuery: JQueryStatic;

In your angular component you should inject a reference to the element and reference the nativeElement property. This will give you a reference to the your components root element, so you would probably want to grab the first child node.

Declaring jQuery variable as JQueryStatic will give you a typed reference to jQuery

/// <reference path="typings/jquery/jquery.d.ts" />
import {bootstrap}    from 'angular2/platform/browser';
import {Component, ElementRef, AfterViewInit} from 'angular2/core';

declare var jQuery:JQueryStatic;

@Component({
    selector: 'ng-chosen',
    template:`<select>
        <option *ngFor="#item of items" [value]="item" [selected]="item == selectedValue">{{item}} option</option>
        </select>
        <h4> {{selectedValue}}</h4>`})
export class NgChosenComponent implements AfterViewInit {
    static chosenInitialized = false;
    items = ['First', 'Second', 'Third'];
    selectedValue = 'Second';

    constructor(private el:ElementRef) {
    }

    ngAfterViewInit() {
        if(!NgChosenComponent.chosenInitialized) {
            jQuery(this.el.nativeElement)
                .find('select')
                .chosen()
                .on('change', (e, args) => {
                    this.selectedValue = args.selected;
            });
            NgChosenComponent.chosenInitialized = true;
        }
    }
}

bootstrap(NgChosenComponent);

This example is avalible on plunker: http://plnkr.co/edit/OH3HMIKl7QmFMCQdqTFm

tslint will complain about chosen not beeing a property on jQuery, to fix this you can add a definition to the jQuery interface in jquery.d.ts

interface JQuery {
    chosen(options?:any):JQuery;
}

declare module "jquery" {
    export = JQuery;
}
declare var jQuery: JQueryStatic;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download