I am trying to open a Bootstrap Modal from an Angular component without using ng-bootstrap(not updated to Angular 14 yet).
I am using bootstrap 4.6, and I have integrated it by installing the npm bootstrap, popper and jquery respectively.
package.json
"jquery": "^3.5.1",
"bootstrap": "^4.6.2",
"@popperjs/core": "^2.11.5",
I also configured angular.json the following way:
"styles": [
"./node_modules/bootstrap/dist/css/bootstrap.css",
"src/styles.css"
],
"scripts": [
"./node_modules/jquery/dist/jquery.js",
"./node_modules/popper.js/dist/umd/popper.min.js",
"./node_modules/bootstrap/dist/js/bootstrap.min.js",
]
In the component I have a modal object (html):
<div id="Modal" #Modal tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">.
...</div>
while on an event in the component .ts, I try:
$('#Modal').modal('show')
but unfortunately, I get the following exception:
core.mjs:7635 ERROR TypeError:.modal is not a function
Is there anything I can do to avoid this kind of exception and open the modal correctly?
Is there also a way to avoid using jquery and using directly @ViewChild?
CodePudding user response:
According to the docs, all plugins depend on jQuery
, so you won't be able to avoid using jQuery.
While it's not recommended to use jQuery and Angular together, it's possible in principle. As you already added it in your package.json
, you just need to declare to jQuery symbol using declare var $: any;
. Read here for further information.
However, I would suggest to avoid using jQuery and Angular both in one project. Have a look at Bootstrap Version 5.x to be independent of jQuery (Bootstrap 5 is designed to be used without jQuery
): https://getbootstrap.com/docs/5.0/components/modal/ – in my opinion, this would fit best to your described use case.