Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2/4 prevent user to leave component if changes not saved

I have this interface that i'm using to prevent the user to leave page

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}

In one of my component i have the following code

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

Can someone tell me what am i doing wrong?

like image 620
user9052661 Avatar asked Dec 04 '17 19:12

user9052661


1 Answers

The issue was caused by lazy loading

Instead of having this in your app routing:

path: 'dashboard',
        canDeactivate: [PendingChangesGuard], <-- causing issue
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

You need to remove the canDeactive from the app routing and move it to the module routing.

const routes: Routes = [
  {
    path: '',
    component: DashboardComponent,
    canDeactivate: [ PendingChangesGuard ]
  }
like image 186
user9052661 Avatar answered Nov 15 '22 07:11

user9052661