2

I am trying to use some jQuery plugins in my angular2 app created with angular-cli.

As described in the doc, I installed the libraries I need using npm and, when available, the types too. I then added styles and scripts in the angular-cli.json, and if I open the chrome debugger I can see that the libraries are correctly loaded.

The problem is that every time I try to use any jQuery plugin, I always get a js error in the console which says "the method is not a function".

I've created a small example using jQuery and fullcalendar, and it's forkable from this GitHub repo.

https://github.com/vmilitello/jquery-plugin

Note: the problem exists only with JQuery plugins that needs a selector to run (like $("#myItem").fullcalendar() or $(".foo").steps()). If you use libraries like Sweetalert, the problem doesn't appear.

I am sure I am missing something, but I really cannot figured it out what it is!

Thank you.

Adeel
  • 2,901
  • 7
  • 24
  • 34

2 Answers2

1

Install ( if you didn't )

npm install @types/jquery --save-dev

You need to write manual typing's for your plugin.

Create structure:

/custom_typings
 /fullcalendar
  /index.d.ts

Than in index.d.ts something like:

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

Than in tsconfig.json

"typeRoots": [
  "../node_modules/@types",
  "../custom_typings"
]
Vlado Tesanovic
  • 6,369
  • 2
  • 20
  • 31
  • My problem is not with types. What you suggest just let me avoid to cast the jQuery selector while I am writing my typescript file. Basically instead of ($("#calendar")).fullcalendar();, I can write $("#calendar").fullcalendar();. But this is barely related to my question. I updated the branch on GitHub to demonstrate that this solution doesn't work. Thank you anyway. – Militello Vincenzo Nov 08 '16 at 14:38
  • name your typing file index.d.ts not index.ts, and jQuery function is not fullcalendar, it is fullCalendar, i tried it on your repo and it works – Vlado Tesanovic Nov 08 '16 at 21:35
  • Thank you! I was actually playing around with some guys on gitter.im, and we found the problem as well. Thank you for updating the branch! Appreciate it. I will leave the branch there hoping that it could help someone else. Thanks! – Militello Vincenzo Nov 08 '16 at 21:49
0

All correct besides one small detail without which it is not working. As mentioned here in the last part, you must have in your component

declare var $:any

Then $ will be global and will see the fullCalendar() function, otherwise it did not work for me.