How can I close a modal in Angular 2?
Apart from the @MattScarpino's answer another alternative is just change your button type to button
from submit
and call your function
submitComments()
and at the same time call dismiss-modal
.
by doing so you able to dismiss modal and call function too at the same time hope this may help you.
here is example:
<button type="button" class="btn btn-info" 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">
<form>
<div class="form-group row">
<label class="form-control-label col-sm-2">Comments:</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" (click)='submitComments()' data-dismiss="myModal" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Update
if you wish to close modal from your controller side you can use using this way
$("#myModal").modal("hide");
Using @ViewChild
add #closeBtn
to the element with data-dismiss="modal"
<a><i class="fa fa-close" data-dismiss="modal" #closeBtn></i></a>
Component html
<div class="modal fade" id="yourModalId">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<a><i class="fa fa-close" data-dismiss="modal" #closeBtn></i></a>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
using this.closeBtn.nativeElement.click();
to trigger click event will close your modal.
Component typescript
import {ViewChild, ElementRef} from '@angular/core';
@Component({
moduleId: ...,
selector: '.',
templateUrl: '.',
styleUrls: ['.']
})
export class yourClass {
@ViewChild('closeBtn') closeBtn: ElementRef;
yourFunction() {
//do something
...
...
//close your modal
this.closeModal();
}
//call this wherever you want to close modal
private closeModal(): void {
this.closeBtn.nativeElement.click();
}
}
You can do it by simply declaring jQuery variable with any type inside Angular2 controller.
declare var jQuery:any;
Add this just after import statements and before component decorator.
Then access bootstrap modal with it's id like this.
jQuery("#myModal").modal("hide");