How to use code to open a modal in Angular 2?
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
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.
Easy way to achieve this in angular 2 or 4 (Assuming that you are using bootstrap 4)
Component.html
<button type="button" (click)="openModel()">Open Modal</button>
<div #myModel class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title ">Title</h5>
<button type="button" class="close" (click)="closeModel()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
</div>
</div>
</div>
Component.ts
import {Component, OnInit, ViewChild} from '@angular/core';
@ViewChild('myModal') myModal;
openModel() {
this.myModal.nativeElement.className = 'modal fade show';
}
closeModel() {
this.myModal.nativeElement.className = 'modal hide';
}