I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away.
Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if it has unsaved changes.
How can I access this child component's form within the guard logic?
Guard:
import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { DialogService } from "ng2-bootstrap-modal";
import { ConfirmComponent } from '../components/confirm/confirm.component';
import { Inject } from '@angular/core';
export interface FormComponent {
form: FormGroup;
}
export class PreventUnsavedChangesGuard implements CanDeactivate<FormComponent> {
constructor(@Inject(DialogService) private dialogService: DialogService) { }
canDeactivate(component: FormComponent): Promise<boolean> {
if (component.form.dirty) {
return new Promise<boolean>((resolve, reject) => {
this.dialogService.addDialog(ConfirmComponent, {
title: 'Unsaved Changes',
message: 'You have unsaved changes. Are you sure you want to navigate away?'
})
.subscribe((isConfirmed) => {
return resolve(isConfirmed);
});
});
}
return Promise.resolve(true);
}
}