How can I use jQuery in an Angular 8 app?

后端 未结 3 1426
南方客
南方客 2020-12-16 03:05

I have an application that utilizes SignalR to communicate with a desktop application. To utilize SignalR I need to use jQuery in my .ts file. However, it doesn\'t seem to w

相关标签:
3条回答
  • 2020-12-16 03:26

    So, after stepping away from the issue for a bit and using roberts answer to confirm jQuery was working in app.module.ts (I wasn't aware a console.log would work in the middle of the imports), I realized I had fought this issue the last time I upgraded v4 to v7.

    What had happened, is a dependency was causing jQuery to be reloaded. The section of the app that starts the signalR communication also loads another dependency (telerik-angular-report-viewer) which was causing console.log($) to display nothing because jQuery hadn't been loaded into the component yet.

    The fix:

    Remove the following code

    window.jQuery = jQuery;
    window.$ = jQuery;
    

    from the following files

    • dependencies\telerikReportViewer.kendo.min.js
    • dependencies\telerikReportViewer.js
    • cjs\telerik-report-viewer.component.js
    • es\telerik-report-viewer.component.js
    0 讨论(0)
  • 2020-12-16 03:29

    Angular 8 works with JQuery.

     "dependencies": {
      ...
      "jquery": "^3.4.1",
      ...
    }
    

    in your angular.json file import the required file like this:

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

    no ./ at the beginning, just node_modules/...

    In your app.module verify it is working like this:

    import { AppComponent } from './app.component';
    
    declare var $: any;
    console.log(`jQuery version: ${$.fn.jquery}`);
    
    @NgModule({
    

    In the developer tools console it should print this:

    jQuery version: 3.4.1

    0 讨论(0)
  • 2020-12-16 03:43

    More elegant way without using

    declare var $: any;
    

    First run

    npm install jquery --save
    npm install @types/jquery --save
    

    Then in scripts section in architect => build of angular.json file add path for jquery lib

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

    Then in your tsconfig.app.json

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": ["jquery"] // add here
      },
      "exclude": ["test.ts", "**/*.spec.ts"]
    }
    

    So now you can use jquery anywhere in your project without using declare var $ : any for every file you need to use jquery

    0 讨论(0)
提交回复
热议问题