angularngx-bootstrapngx-bootstrap-modal

How to trigger modals using show


I'm using this.myModal1.show() & this.myModal2.show() to open the modals. But It is always triggering myModal1

My component.ts

@ViewChild(ModalDirective) myModal1: ModalDirective;
@ViewChild(ModalDirective) myModal2: ModalDirective;

My component.html

<div class="modal fade" bsModal #myModal1="bs-modal"
     tabindex="-1" role="dialog" aria-labelledby="dialog-events-name">
  <div class="modal-dialog otp-modal">
    <div class="modal-content">
        ...
    </div>
  </div>
</div>

<div class="modal fade" bsModal #myModal2="bs-modal"
     tabindex="-1" role="dialog" aria-labelledby="dialog-events-name">
  <div class="modal-dialog otp-modal">
    <div class="modal-content">
        ...
    </div>
  </div>
</div>

Solution

  • You should pass reference id to Viewchild instead of ModalDirective

    Because with ModalDirective it always targets first element with that directive.

    @ViewChild('myModal1') myModal1: ModalDirective;
    @ViewChild('myModal2') myModal2: ModalDirective;
    

    Here is Stackblitz link with this implemented.

    https://stackblitz.com/edit/angular-ngx-bootstrap-p6ohpe

    Also see Docs here https://angular.io/api/core/ViewChild

    You can use ViewChild to get the first element or the directive matching the selector from the view DOM.