7.2: Add CanDeactivate Guard

Right now, if our user is editing their profile and they click away - all of their changes will be lost.

We can add a guard that sends a dialogue box asking them to confirm if they want to navigate away and lose their changes. Instead of a guard to protect a route form being activated as we've done previously - we can add a guard that prevents a route from being deactivated.

Adding Guard

In the guards folder, add a new file called prevent-unsaved-changes.guard.ts.

@Injectable()
export class PreventUnsavedChanges implements CanDeactivate<MemberEditComponent> {

    canDeactivate(component: MemberEditComponent) {
        if (component.editForm.dirty) {
            return confirm('Are you sure you want to continue? Any unsaved changes will be lost.');
        }
        return true;
    }
}

We'll also need to import it into our app.module.ts file and add it to the providers array:

import { PreventUnsavedChanges } from './guards/prevent-unsaved-changes.guard';

//  ...

providers: [
    AuthService,
    UserService,
    AuthGuard,
    MemberDetailResolver,
    MemberListResolver,
    ErrorInterceptorProvider,
    AlertifyService,
    MemberEditResolver,
    PreventUnsavedChanges
],

Adding Guard to Route

In routes.ts, add the new Guard to the MemberEditComponent route:

children: [
    { path: 'members', component: MemberListComponent, resolve: {users: MemberListResolver } },
    { path: 'members/:id', component: MemberDetailComponent, resolve: { user: MemberDetailResolver }},
    { path: 'member/edit', component: MemberEditComponent,
        resolve: { user: MemberEditResolver }, canDeactivate: [PreventUnsavedChanges] },                    //  <--- Added
    { path: 'messages', component: MessagesComponent },
    { path: 'followers', component: FollowersComponent },
]

Last updated