1. How do you prevent navigating away when there are unsaved form changes?
Create a CanDeactivate guard that asks the component if it’s safe to leave, optionally showing a confirm dialog. The guarded component exposes a method like hasUnsavedChanges().
export interface ExitCheck { hasUnsaved(): boolean; }
@Injectable({ providedIn:'root' })
export class ExitGuard implements CanDeactivate<ExitCheck> {
canDeactivate(cmp: ExitCheck){
return cmp.hasUnsaved() ? confirm('Discard changes?') : true;
}
}
{ path: 'edit/:id', component: EditComponent, canDeactivate:[ExitGuard] }