Search code examples
angularbootstrap-modal

How to use code to open a modal in Angular 2?


Usually we use data-target="#myModal" in the <button> to open a modal. Right now I need use codes to control when to open the modal.

If I use [hidden] or *ngIf to show it, I need remove class="modal fade", otherwise, the modal will never show. Like this:

<div [hidden]="hideModal" id="myModal">

However, in this case, after removing class="modal fade", the modal won't fade in and has no shade in the background. And what's worse, it will show at the screen bottom instead of screen center.

Is there a way to keep class="modal fade" and use code to open it?

<button type="button" data-toggle="modal" data-target="#myModal">Open Modal</button>

<div id="myModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
    </div>
  </div>
</div>

Solution

  • This is one way I found. You can add a hidden button:

    <button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>
    

    Then use the code to "click" the button to open the modal:

    document.getElementById("openModalButton").click();
    

    This way can keep the bootstrap style of the modal and the fade in animation.