Amin Kamalinia
Amin Kamalinia

Reputation: 334

Problem with opening bootstrap 5 modal via typescript

As you may know bootstrap 5 has been released and for opening modal via JavaScript the official website offer the code below.

var myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
myModal.toggle()

The problem is I am developing front-end application via Angular 11 strict mode so in this case typescript does not allow me to use new bootstrap.Modal because it is not exist. So please tell me any solutions.

Upvotes: 5

Views: 10954

Answers (2)

Kwizera Valens
Kwizera Valens

Reputation: 5

If you are using bootstrap from CDN, you may do the following:

var myModal: any = new (window as any).bootstrap.Modal(
   document.getElementById("my-modal")
);

I hope that this will help :)

Upvotes: -3

Felipe
Felipe

Reputation: 11959

If you are trying to use bootstrap with typescript, you will most likely be needing some typings to go along with it. Your setup may vary a bit, but looking at the documentation and using the typings from NPM, you can probably get started with

npm install bootstrap@next @types/bootstrap

at this point, if you need to instantiate a plugin, i.e. a modal, the docs specify

const bootstrap = require('bootstrap') or import bootstrap from 'bootstrap' will load all of Bootstrap’s plugins onto a bootstrap object. The bootstrap module itself exports all of our plugins. You can manually load Bootstrap’s plugins individually by loading the /js/dist/*.js files under the package’s top-level directory.

In your particular case, I believe what you are trying to do is something akin to the following:

import 'bootstrap/dist/css/bootstrap.css';
import { Modal } from 'bootstrap';

const element = document.getElementById('myModal') as HTMLElement;
const myModal = new Modal(element);
myModal.show();

Upvotes: 14

Related Questions