Rahul Kundu
Rahul Kundu

Reputation: 125

Prevent Bootstrap Modal close on Esc key press

I am using NGX Bootstrap modal in my project. Inside the modal i have a form, right now if I press Esc key the modal is hiding.

How can I be able to show child modal(confirm modal) if any user is filling up the form and suddenly press the esc key or tries to close the parent modal.

Is there any way to show the child modal without closing the parent modal based on some condition if anyone presses the esc key.

    <button type="button" class="btn btn-primary" (click)="parentModal.show()">Open parent modal</button>

    <!-- parent modal -->

    <div class="modal fade" bsModal #parentModal="bs-modal" tabindex="-1" role="dialog" aria-labelledby="dialog-nested-name1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h4 id="dialog-nested-name1" class="modal-title pull-left">First modal</h4>
            <button type="button" class="close pull-right" aria-label="Close" (click)="parentModal.hide()">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form>
               <div class="form-control">
                  <input type="text" placeholder="email" />
               </div>
               <div class="form-control">
                  <input type="text" placeholder="password" />
               </div>
               <button type="submit" class="btn-primary"></button>
            </form>
          </div>
        </div>
      </div>
    </div>

   <!-- confirmation modal --> 

    <div class="modal fade" bsModal #childModal="bs-modal" tabindex="-1" role="dialog" aria-labelledby="dialog-nested-name2">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 id="dialog-nested-name2" class="modal-title pull-left">Second modal</h4>
            <button type="button" class="close pull-right" aria-label="Close" (click)="childModal.hide()">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            Are you want to exit? Your changes will not be saved.<br>
            <button class="btn-danger">Discard</button>
            <button class="btn-primary">continue</button>
          </div>
        </div>
      </div>
    </div>

Upvotes: 3

Views: 5373

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

Assuming you are using ng-bootstrap.

While using modal.open method you can pass keyboard attribute as false.

Its official doc can be found at :- https://ng-bootstrap.github.io/#/components/modal/api

Eg:- this.ngbModal.open(content, {keyboard: false});

Upvotes: 2

Related Questions