Reddy Bhavani Prasad
Reddy Bhavani Prasad

Reputation: 1115

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>

Upvotes: 0

Views: 1583

Answers (3)

BeeBee8
BeeBee8

Reputation: 3074

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.

Upvotes: 1

Ryan Huang
Ryan Huang

Reputation: 726

Try change:

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

To:

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

Upvotes: 1

Gbacc
Gbacc

Reputation: 150

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;

Upvotes: 1

Related Questions