Angular CLI:__ WWEPACK_IMPORTED_MODULE_1_jquery __(...).collapse不是函数

ahe*_*ick 9 jquery twitter-bootstrap angular

我有一个通过CLI(Angular 4)生成的Angular App组件.

我带来了jQuery + Bootstrap,如下所示:

  "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
  ],
  "scripts": ["../node_modules/jquery/dist/jquery.min.js",
              "../node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],
Run Code Online (Sandbox Code Playgroud)

我的App Component看起来像这样:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [

    './app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'app';

  constructor() { }

  ngAfterViewInit() {

    $('.nav a').click(function () {
        $('.navbar-collapse').collapse('hide');
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

收到以下错误:

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).collapse is not a function
Run Code Online (Sandbox Code Playgroud)

Bootstrap没有正确导入吗?我已经尝试将以下内容添加到我的组件顶部:

import 'bootstrap/dist/js/bootstrap.js';
Run Code Online (Sandbox Code Playgroud)

编辑:

有一点我注意到了.在浏览器中运行时,如果我通过Chrome控制台执行以下行,则可以正常运行:

$('.navbar-collapse').collapse('hide');
Run Code Online (Sandbox Code Playgroud)

这有什么区别?我肯定错过了什么.

Kar*_*iri 15

以下步骤为我解决了这个问题。

我替换了组件中的jquery import命令

import * as $ from 'jquery';
Run Code Online (Sandbox Code Playgroud)

declare var $ : any;
Run Code Online (Sandbox Code Playgroud)

  • 这个变化实际上是什么?它为我工作。只是好奇 (2认同)

Kri*_*van 5

正如评论中提到的,这似乎是 Bootstrap 的一个问题,要求 jquery 是全局的。以下链接回答了一个非常相似的问题:-

Angular 组件中的 2 个 fullcalender 实例导致找不到 jquery 错误

另一个选项是定义折叠类型,如 -cloud 的回答中所述