Reputation: 855
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 class="modal fade" 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?
Upvotes: 0
Views: 2317
Reputation: 5550
Bootstrap 5
use the @ViewChild
<button type="button" #test class="btn btn-primary invisible" data-bs-toggle="modal" data-bs-target="#android-modal">Launch demo modal</button>
<div class="modal fade" id="android-modal" tabindex="-1" aria-labelledby="android-modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="android-modalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
in the ts file get the Button element with the ViewChild and use the click event
in order to get the element you have to implement the AfterViewInit
export class ModalComponent implements AfterViewInit
@ViewChild("test") modal: ElementRef | undefined
ngAfterViewInit(): void { this.modal?.nativeElement.click(); };
Upvotes: 0
Reputation: 2453
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.
Upvotes: 1