Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 432
Hongbo Miao Avatar asked Feb 15 '16 02:02

Hongbo Miao


People also ask

How do I open a typescript modal?

Display is a defined variable in angular typescript and by default it is none. display='none'; Next, For opening the model window, click the open modal() and change the display variable value as a block.

How do I open a modal when I click a button?

To trigger the modal window, you need to use a button or a link. Then include the two data-* attributes: data-toggle="modal" opens the modal window. data-target="#myModal" points to the id of the modal.

How do you call a modal in Javascript?

To open a modal, we'll need any element with the data-open attribute (normally a button ). The value of this attribute should be the ID of the desired modal. By default, a modal will close if we click outside its boundaries or when the Esc key is pressed.


2 Answers

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.

like image 90
Hongbo Miao Avatar answered Sep 19 '22 16:09

Hongbo Miao


Include jQuery as usual inside script tags in index.html.

After all the imports but before declaring @Component, add:

declare var $: any; 

Now you are free to use jQuery anywhere in your Angular 2 TypeScript code:

$("#myModal").modal('show'); 

Reference: https://stackoverflow.com/a/38246116/2473022

like image 35
Moobie Avatar answered Sep 19 '22 16:09

Moobie