Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 ReferenceError: $ is not defined error with JQuery

I have installed angular 6 with foundation but I am getting an error with JQuery.

Uncaught syntaxerror: unexpected identifier ReferenceError: $ is not defined

In my component, i have

declare var $:any

onNgInit () {
  $(document).foundation()
}

I have all imports in my angular.json

scripts : [
  "node_modules/jquery/dist/jquery.js"
]

I have tried everything I found on the internet but still facing the same error. Also to add this used to work when I was working with Angular 4

like image 900
user3701188 Avatar asked Jun 11 '18 08:06

user3701188


People also ask

How do I fix uncaught ReferenceError is not defined in jQuery?

To solve this error, we simply add the jQuery CDN link or downloaded jQuery path link inside the head section. Example: This example resolves the error by adding the required CDN link inside the <script> tag.

How do I fix resolve ReferenceError is not defined?

Answer: Execute Code after jQuery Library has Loaded The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.

Is not defined issue in jQuery?

jQuery is not defined” is a common WordPress error that occurs when a website calls for a jQuery function before the library properly loads. Possible causes include conflicting plugins, a corrupted jQuery file, a blocked CDN, or your JavaScript code loads incorrectly.”

Why uncaught ReferenceError is not defined?

While programming in JavaScript, jQuery or Angular JS, coders often encounter an error called Uncaught ReferenceError: $ is not defined. This usually happens when the $, that may be a variable or a method is not properly defined but is being used.


2 Answers

This is something related to the way ES6 modules isolation works. Loading from the angular.json file is the same as the script tag on an index.html file (the global scope). When you import it on any component you're getting a new local copy, so avoid importing it this way.

To prevent intellisense and compiling issues, create a typings.d.ts file with the following content:

declare var $: any;
declare var jQuery: any;

Now you're ready to go :)

like image 109
elvin Avatar answered Sep 17 '22 08:09

elvin


Install Jquery Plugin For angular

npm install jquery --save

Now in your app.module.ts add

import * as $ from "jquery";

It will make the work done.

like image 31
BlizZard Avatar answered Sep 21 '22 08:09

BlizZard