1

I'm trying to close/hide bootstrap5 modal using JavaScript in angular, the problem that the hide function in bootstrap notworking somehow, so what I'm trying to do is to click a button that have data-bs-dismiss and it's work if I click it manually but not working if I try to do it via JavaScript.

<div class="modal fade" id="#modalId" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true"
    data-toggle="modal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">

            <div class="modal-body">
                    <button id="modalDismiss" data-bs-dismiss="modal" aria-hidden="true">Test</button>
            </div>
            <div class="modal-footer">

            </div>
        </div>
    </div>
</div>
document.getElementById('modalDismiss').click(); // notwoking
new window.bootstrap.Modal(document.getElementById('modalId')).hide(); //trying this same problem :(
new window.bootstrap.Modal(document.getElementById('modalId')).show(); //trying to show the modal works fine idon't why the hide function not working for me.

I trace the click event for the modalDismiss and found that the event that close the modal enter image description here

I don't know if this relevant to the problem.

MahmouD Skafi
  • 370
  • 3
  • 15

1 Answers1

0

complete demo in this Stackblitz Demo

Basically, you need to import modal class from import { Modal } from 'bootstrap'; .

when Modal opened then you need to assign modal reference to this modal class and then create new instance.

 open(element: any): void {
   this.modalDirect = new Modal(element, {});
   this.modalDirect.show();
 }

and then, when you click on close button then call this close method.

close() {
  this.modalDirect.hide();
}

complete code you can find out in attached stackblitz lik.

Developer
  • 3,309
  • 2
  • 19
  • 23