2
votes

I have an Angular 8 project that is using bootstrap. I am trying to show the modal dialog inside my component using the $('myModal').modal('show') inside my component's Typescript file.

Here's my component's file:

import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
// import * as $ from 'jquery';
import * as bootstrap from 'bootstrap';

@Component({
  selector: 'app-xyz',
  templateUrl: './xyz.component.html',
  styleUrls: ['./xyz.css']
})
export class XyzComponent implements OnInit {

  constructor(private router: Router) {
  }

  ngOnInit() {
  }

  submit() {
    $('#confirm').modal('show');
  }

}

Upon invoking the submit() funciton on click I get the following error: ERROR TypeError: $(...).modal is not a function

I installed bootstrap and jquery using npm install bootstrap --save and npm install jquery --save.

I even installed ngx-bootstrap.

However, when I uncomment the line importing jQuery I get a different error: ERROR TypeError: jquery__WEBPACK_IMPORTED_MODULE_3__(...).modal is not a function

1
you don't import jquery... - Bharat Chauhan
It's better to use angular material dialog. material.angular.io/components/dialog - Bharat Chauhan
"better to use angular material dialog"... but he's not using material, he's using bootstrap. - UncleDave
As you've already installed ngx-bootstrap consider using their modal. Try not to mix jQuery and Angular, generally you don't need to. - UncleDave

1 Answers

1
votes

Check your angular.json file to make sure that the Jquery js file is included in your scripts array.

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

Then in your component TS file declare var $ instead of trying to import it:

declare var $: any;

That should allow you to trigger the modal via

$('#confirm').modal();

Also make sure that the HTML is correct. Example Modal:

<div class="modal fade" id="confirm" tabindex="-1" role="dialog" data-backdrop="static" aria-labelledby="noDataModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background-color:lightgrey">
                <h5 class="modal-title" id="noDataModalLongTitle">No Data</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <i class="fas fa-check fa-4x mb-3 animated rotateIn"></i>
                No Data Found. Please expand your search criteria and try again.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Ok</button>
            </div>
        </div>
    </div>
</div>

Hope this helps!