Reputation: 21
I have a pretty basic modal that is being used to let a user enter notes
openNotes(conquest) {
const modalRef = this.modalService.open(EditNotesModalComponent);
modalRef.result.then((result) => {
console.log('closed', result);
},
(reason) => {
console.log('dismissed', reason);
});
return modalRef;
}
What I'd like to do is, in the event that the user closes the modal when there is an unfinished note, show another modal that will remind them that they have unsaved work that will be lost if they close the modal. I would like the user to then be able to choose to keep editing (in which case the second modal will close and the first modal will remain open) or discard their work (in which case both modals would close).
It's easy enough to connect something like this to custom modal closing actions, such as the user manually clicking a button that would normally close the modal. The problem I am having is that I do not seem to be able to know when the user has dismissed the modal via clicking outside the modal or hitting the ESC key.
In UibModal for AngularJS, you could catch such events with something like this:
$scope.$on('modal.closing', (event) => {
if (this.newNote.length > 0) {
event.preventDefault();
this.openConfirmModal();
}
});
and then, depending on how the confirmation modal resolves, one can decide to either close the modal or keep it open. Is something like this possible for NgbModal in Angular 4?
Thanks!
Edit: I know about the beforeDismiss function on in NgbModalOptions, but AFAIK you can't pass any parameters to this function. I would like the confirmation modal to pop up only when the user has unfinished notes in the modal.
Upvotes: 1
Views: 3031
Reputation: 6163
You can use @Viewchild
to get a reference to the input field in the modal, then use the beforeDimiss
function to get the text typed by the user.
The following example has a modal with a <textarea>
and when the modal is dismissed (either by clicking the backdrop or pressing ESC), the value in the textarea is logged to the console.
HTML
In the HTML, add a template reference variable to the input field:
<div class="modal-body">
<textarea #myTextarea></textarea>
</div>
Modal Component TypeScript
In the modal component TS file, get a reference to the input field using @ViewChild
:
@ViewChild('myTextarea') textarea;
Parent Component Typescript
In the component where the modal is opened from, add the following beforeDimiss
function. The line modalRef.componentInstance.textarea.nativeElement.value
will get the value from the input field:
open() {
const modalRef = this.modalService.open(NgbdModalContent, {
beforeDismiss: () => {
console.log('The text typed by the user before the modal was dimissed was:')
console.log(modalRef.componentInstance.textarea.nativeElement.value)
return true;
}
});
}
Please see this StackBlitz for a demo.
Upvotes: 1