Sunday, 29 April 2018

How to use jQuery with Angular?



Can anyone tell me, how to use jQuery with Angular?



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



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



tsd install jquery --save
or

typings install dt~jquery --global --save


TypescriptDefinitions are not required since you could just use any as the type for $ or jQuery



In your angular component you should reference a DOM element from the template using @ViewChild() After the view has been initialized you can use the nativeElement property of this object and pass to jQuery.



Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to jQuery.



import {bootstrap}    from '@angular/platform-browser-dynamic';

import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;

@Component({
selector: 'ng-chosen',
template: `

{{selectedValue}}

`
})

export class NgChosenComponent implements AfterViewInit {
@ViewChild('selectElem') el:ElementRef;
items = ['First', 'Second', 'Third'];
selectedValue = 'Second';

ngAfterViewInit() {
$(this.el.nativeElement)
.chosen()
.on('change', (e, args) => {
this.selectedValue = args.selected;

});
}
}

bootstrap(NgChosenComponent);


This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview



tslint will complain about chosen not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file




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

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...