user5500750 user5500750 - 1 year ago 285
Javascript Question

Angular NgbModal beforeDismiss not working

I would like to add a class to the pop up modal before it is closed and then wait for a while before closing it. Looking at the documentation it looks like I can archive this with

beforeDismiss
in the
NgbModalOptions
options; https://ng-bootstrap.github.io/#/components/modal/examples

But it does not work. Here is my open method;

open(content) {
const options : NgbModalOptions = {
size: 'lg',
windowClass: 'animated bounceInUp',
beforeDismiss: () => {
setTimeout(()=>{
alert ('Hello!');
},2000);
return false;
}
};
this.modalRef = this.modalService.open(content, options).result.then((result) => {
//this.closeResult = `Closed with: ${result}`;
}, (reason) => {
//this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
console.log (this.modalRef);
}


I don't mind closing it from outside if that is possible. For example something like
this.modalRef.close
but this shows an error modalRef.close is not a function.

Update



This is my HTML;

<ng-template #content let-c="close" let-d="dismiss">
<div class="modal-header">
<h4 class="modal-title">Save As Site Product Settings</h4>
<button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
{{product.title}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" (click)="saveProductAs()">Save As Site Product</button>
<button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
</div>
</ng-template>


I have discovered that it does not work on just this
<button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
But works on the cross icon. How do I get it to work on
c('Close click')
?

Answer Source

The beforeDismiss function is called before the modal is dismissed but not before the modal is closed (there is a difference between close and dismiss).

As you have the following in the modal template:

<ng-template #content let-c="close" let-d="dismiss">

you would have to call d() rather than c() to hook into the beforeDismiss button when the "Close" button is pressed:

<button type="button" class="btn btn-outline-dark" (click)="d('Close click')">Close</button>

See this Plunker for a demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download