How to trigger modals using show

1.5k Views Asked by At

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>
3

There are 3 best solutions below

9
On BEST ANSWER

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.

0
On

This is because @ViewChild(ModalDirective) will target the first element using ModalDirective.

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.

I think you should use template reference variable like this :

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

Try change:

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

To:

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