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>
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With