Using jQuery with Angular 2, if we are using typescript (5, 6 and 7 versions) we should first add jQuery reference definition.
tsd install jquery --save
OR
typings install dt~jquery --global –save
And also we need to add the ts reference file.
/// <reference path="../typings/jquery/jquery.d.ts" />
Then make the necessary imports
import {bootstrap} from 'angular2/platform/browser'; import {Component, ElementRef, AfterViewInit} from 'angular2/core';
Now, declare jQuery module and the declaring jQuery variable as JQueryStatic will give us a typed reference to jQuery.
1 2 3 4 | declare module "jquery" { export = jQuery; } declare var jQuery: JQueryStatic; |
In the last, write the class and components
1 2 3 4 5 6 7 8 9 10 11 12 | @Component({ selector: 'customer-app', templateUrl: 'index.html' }) export class CustomerComponent implements AfterViewInit { constructor(private el:ElementRef) { } ngAfterViewInit() { if(!CustomerComponent.chosenInitialized) { //TODO: your logic jQuery(this.el.nativeElement)… } } } |
This live demo example,
For more detail go to links,
I
hope you are enjoying with this post! Please share with you friends. Thank you
so much!