1

I want to use Jquery in my Angular2 application. I did the following:

  • I installed using npm package.json

    "devDependencies": {
      "@types/jquery":"2.0.42"
    }
    
  • I created a jQuery.service.ts file and declared an OpaqueToken to expose this library

    import { OpaqueToken } from '@angular/core'
    
    export let JQ_TOKEN = new OpaqueToken('jQuery');
    
  • I imported and declared the jQuery token in app.module.ts

    import {JQ_TOKEN} from './common/jQueryService'
    declare let jQuery : Object;
    

Now I am trying to access the $ of jQuery in my component.ts file

import {JQ_TOKEN} from './jQueryService'

export class simpleModal {
  @ViewChild('sessionModal') contentEl : ElementRef;

  constructor(private elRef : ElementRef, @Inject(JQ_TOKEN) private $ : any){}

  closeModal() {
    this.$(this.contentEl.nativeElement).modal('hide');
  }
}

And I get the following error:

Error: No provider for Token jQuery!

Can someone please guide me on why this error appears?

Powkachu
  • 2,170
  • 2
  • 26
  • 36
ASR
  • 421
  • 11
  • 27
  • Possible duplicate of [How to use jQuery with Angular2?](http://stackoverflow.com/questions/30623825/how-to-use-jquery-with-angular2) – Adnan Umer May 05 '17 at 08:56
  • 1
    The link that you mentioned does not implement exposing jQuery with Opaque Tokens. I want to expose my third party service with Opaque Tokens – ASR May 05 '17 at 09:06

1 Answers1

2

please include jquery file in your index.html and

declare jQuery like this declare var jQuery:any; in your component and you can use it no need to include extra things.

Anku Singh
  • 914
  • 6
  • 12
  • 2
    although this works, it makes your code very hard to test because you're not relying on a global instead of an injected service. – Joseph Eames Jun 15 '17 at 15:38