Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular CLI: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).collapse is not a function

I have an Angular App Component generated via the CLI (Angular 4).

I've brought in jQuery + Bootstrap like so:

  "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"
  ],

My App Component looks like so:

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');
    });
  }
}

Receiving the following error:

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).collapse is not a function

Is Bootstrap not being imported properly? I've tried adding the following to the top of my component:

import 'bootstrap/dist/js/bootstrap.js';

EDIT:

One thing I've noticed. When running in the browser if I execute the following line through the Chrome Console it works without issue:

$('.navbar-collapse').collapse('hide');

What would be the difference here? I must be missing something.

like image 817
aherrick Avatar asked Jul 06 '17 01:07

aherrick


3 Answers

The below step resolved this issue for me..

I replaced the jquery import command in the component from

import * as $ from 'jquery';

to

declare var $ : any;
like image 174
Karthikeyan Vellingiri Avatar answered Oct 17 '22 17:10

Karthikeyan Vellingiri


As mentioned in the comment , it seems to be an issue of Bootstrap requiring jquery to be global. A very similar question is answered in the following link :-

2 fullcalender instances in Angular component causes jquery not found error

The other option is define types for collapse as mentioned in -cloud's answer

like image 6
Krishnanunni Jeevan Avatar answered Oct 17 '22 17:10

Krishnanunni Jeevan


You should not specify your dependencies like that.

Since you've installed bootstrap and jQuery via npm/yarn, you ought to import them directly like import * as $ from 'jquery'; without configure something else. No scripts is needed.

scripts config is supposed to be treated as global script as script tag inside index.html, see the scripts story here.

Since collapse is a jquery plugin from bootstrap, you should do something like

interface JQuery {
  collapse(options?: any): any;
}

to let typescript know its types.

update #1

you can install @types/bootstrap to skip defining the interfaces.

like image 4
e-cloud Avatar answered Oct 17 '22 16:10

e-cloud