In my Angular 4 application I have some components with a form, like this:
export class MyComponent implements OnInit, FormComponent {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({...});
}
they use a Guard service to prevent unsubmitted changes to get lost, so if the user tries to change route before it will ask for a confirmation:
import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
export interface FormComponent {
form: FormGroup;
}
export class UnsavedChangesGuardService implements CanDeactivate<FormComponent> {
canDeactivate(component: FormComponent) {
if (component.form.dirty) {
return confirm(
'The form has not been submitted yet, do you really want to leave page?'
);
}
return true;
}
}
This is using a simple confirm(...)
dialog and it works just fine.
However I would like to replace this simple dialog with a more fancy modal dialog, for example using the ngx-bootstrap Modal.
How can I achieve the same result using a modal instead?
I solved it using ngx-bootstrap Modals and RxJs Subjects.
First of all I created a Modal Component:
here's the template:
Then I modified my guard using a Subject, now it look like this:
In app.module.ts file go to the @NgModule section and add the ConfirmLeaveComponent component to entryComponents.