We have requirement where we have to alert user if page is touched, if use select different menu application should show alert with Yes or No if user continue to proceed then only redirect should occur else it should fall back to the same page. We have tried with ngOnDestroy but, application is redirecting to next page without showing Alert.
My first approach was:
ngOnDestroy()
{
this.touched = this.eventForm.touched;
if (this.touched)
this.display = true;
}
Now I am trying with CanDeactivate
guard (refer to this plunker for an example):
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { SidebarComponent } from './shared/sidebar/sidebar.component';
@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> {
canDeactivate(target: SidebarComponent) {
if (target.hasChanges()) {
return window.confirm('Do you really want to cancel?');
}
return true;
}
}