4

I am trying to use jquery in angular2 and got this error: ReferenceError: $ is not defined from the following code.

declare var $:JQueryStatic;

export class AppComponent {    

ngOnInit() {    

    var container = $("#contact-us-form");    

    container.css("width", $(document).width()).css("height", $(document).height()).hide();    

    container.find(".modal-content .button-close").click(function(){ this.toggleModalWindow("contact-us-form"); });    

    $("#contact-link").click(function(){ this.toggleModalWindow("contact-us-form"); });    

   }     
}      

How could I resolve this ?

10
  • /*Jquery is installed using typings install dt~jquery --global --save. Getting error in var container = $("#contact-us-form"); line saying that $ is not defined. */ Commented Aug 2, 2016 at 5:49
  • Could you explain the purpose of the declaration declare var $:JQueryStatic;? Commented Aug 2, 2016 at 6:07
  • I want to use $.. So. In fact I want to write jquery stuffs Commented Aug 2, 2016 at 6:11
  • Well... $ is a very special character both for Angular and JQuery. Try using some other variable name and see if you still get the error. Commented Aug 2, 2016 at 6:13
  • I just used 'Jq', n i am getting 'Jq is not defined in [null]' Commented Aug 2, 2016 at 6:17

3 Answers 3

4

add angular-cli.json

 "../node_modules/jquery/dist/jquery.js"

Have a typescript file

  import * as $ from "jquery";

install jquery using npm

Sign up to request clarification or add additional context in comments.

Comments

4

FOLLOW THESE STEPS:

  1. npm i jquery --save
  2. npm i @types/jquery -D
  3. import * as $ from 'jquery'---> in app.module.ts

That should do the trick and no need to put declare var jQuery: any; or declare var $: any; in each file.

1 Comment

Steps are working. Please add some comments with steps to explain.
0

Try these Steps-

  1. npm install jquery @types/jquery --save
  2. go to angular.json in the project, add 'node_modules/jquery/dist/jquery.min.js' in the scripts: [ ].
  3. Reload project.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.