ng.newbie
ng.newbie

Reputation: 3218

Cannot use Bootstrap JS in Angular2

I am using angular-cli to create a project that uses some of the bootstrap js functions like button() and modal(), but the problem is that while I am able to compile my ts file perfectly when I actually try to execute the javascript function in the browser it fails with

error_handler.js:53 TypeError: button.button is not a function
    at NewdeviceComponent.loading (newdevice.component.ts:122)
    at NewdeviceComponent.add (newdevice.component.ts:97)
    at CompiledTemplate.proxyViewClass.View_NewdeviceComponent0.handleEvent_67 (component.ngfactory.js:517)
    at CompiledTemplate.proxyViewClass.<anonymous> (view.js:408)
    at HTMLButtonElement.<anonymous> (dom_renderer.js:276)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.js:227)
    at ZoneDelegate.invokeTask (zone.js:264)
    at Zone.runTask (zone.js:154)
    at HTMLButtonElement.ZoneTask.invoke (zone.js:335)

I am invoking the button function on after a click event like the following-:

button.button(loading ? 'loading' : 'reset');

The weird part is that VSCode gives me intelli sense and compilation actually succeeds but fails in the browser.

All the bootstrap files and styles sheets are globally loaded from the angular-cli.json.

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

Upvotes: 1

Views: 1571

Answers (1)

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

Using Bootstrap's JS means that you would have to load jQuery, Bootstrap's JS and potentially create Angular wrappers around Bootstrap's JS code. But even doing so would result in rather poor integration since both jQuery and Angular would "fight" over DOM updates - the philosophy of those 2 libraries is very different.

In Angular context it is better to use a dedicated, native libraries that provide much better API for the Angular users. There is an excellent implementation for Angular and Bootstrap 4: https://ng-bootstrap.github.io. By using it you could skip the whole jQuery / Bootstrap JS story.

Upvotes: 1

Related Questions