[Fixed] Problem with opening bootstrap 5 modal via typescript

Issue

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.

Solution

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 [email protected] @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();

Leave a Reply

(*) Required, Your email will not be published