Sta-Dev
Sta-Dev

Reputation: 305

Uncaught Reference error $ is not defined in Angular

I am having some jquery script in "/src/assets/js/auth.js".

I have included the file and jquery plugin in angular.cli.json file.

angular.cli.json:

"scripts": [
    "../src/assets/js/auth.js",
    "../../node_modules/jquery/dist/jquery.min.js"
  ],

Finally I have imported jquery in the app.component.ts.

app.component.ts:

import * as $ from 'jquery';

To make sure whether jquery works or not, I have put the jquery code in ngOnInit() {} function and its works well.

But when I am placing it as an external js file, I will always return the error: Uncaught Reference error $ is not defined

Please someone help me to fix this issue.

Upvotes: 1

Views: 7059

Answers (1)

David
David

Reputation: 34475

You need to include jquery file before the plugin

"scripts": [
"../../node_modules/jquery/dist/jquery.min.js"
"../src/assets/js/auth.js",
  ],

And replace

import * as $ from 'jquery';

with

declare let $: any;

Otherwise, jquery will work but $ will not contain the plugin's function

Upvotes: 3

Related Questions