首页 > 解决方案 > 如何在 Angular 6 中使用 jquery-ui

问题描述

我已经尝试了在 StackOverflow 上发布的许多方法,以在 Angular 6 组件中使用jquery - ui ,但它们都没有奏效。例如,

  1. 我运行npm install jquery jquery-ui来安装 jquery 和 jquery-ui。

  2. 包含在 angular.json 中

    “脚本”:[“node_modules/jquery/dist/jquery.js”,“node_modules/jquery-ui-dist/jquery-ui.js”,

错误如下:

AppComponent_Host.ngfactory.js [sm]:1ERROR TypeError: jquery__WEBPACK_IMPORTED_MODULE_1__(...).slider is not a function
    at AppComponent.push../src/app/app.component.ts.AppComponent.ngAfterContentInit (http:||localhost:4200/main.js:154:56)
    at callProviderLifecycles (http:||localhost:4200/vendor.js:42663:18)
    at callElementProvidersLifecycles (http:||localhost:4200/vendor.js:42644:13)
    at callLifecycleHooksChildrenFirst (http:||localhost:4200/vendor.js:42634:29)
    at checkAndUpdateView (http:||localhost:4200/vendor.js:43565:5)
    at callWithDebugContext (http:||localhost:4200/vendor.js:44454:25)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (http:||localhost:4200/vendor.js:44132:12)
    at ViewRef_.push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges (http:||localhost:4200/vendor.js:41948:22)
    at http:||localhost:4200/vendor.js:37684:63
    at Array.forEach (native)

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Car Dealer</title>
</head>
<body>
  <app-root></app-root>
</body> 
</html>

app.component.html

<div id="slider">
</div>

app.component.ts

import { Component, AfterContentInit } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  title = 'MDK';

  ngAfterContentInit() {
    $( "#slider" ).slider({
      range: true,
      values: [ 17, 67 ]
    });
  }
}

另一篇文章建议我根本不应该使用angular.json 的 angular 6,而是使用 index.html 来包含脚本,但它也没有奏效。

我在 index.html 中包含以下内容,但即便如此,同样的错误也出现了

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

标签: javascriptjqueryangularjquery-uiangular6

解决方案


如果你写

import * as $ from 'jquery';

那么只有jquery(而不是额外的插件,如jquery-ui)的代码将由打字稿编译器导入到$变量中。

如果你使用

 declare let $: any;

然后你只是通知打字稿这个变量存在。在这种情况下,$将包含您导入的脚本中分配给它的任何内容angular.json,即jqueryANDjquery-ui插件


推荐阅读