Reputation: 65
We know that there is a method ngOnDestroy() in angular which runs on destroying a component but I want to know that is there any way to prevent it from destroying?
Upvotes: 5
Views: 7324
Reputation: 1538
The CanDeactivate guard has access to the instance of the active component, so you can implement a hasChanges() that check if there have been changes and conditionally ask for the user confirmation before leave. In the following example the CanDeactivateComponent implements the methods hasChanges() that returns a boolean value indicating if the components has detected any changes. The implementation of CanDeactivate guard is similar to the CanActivate guard implelementaion (you can create a function, or a class that implements the CanDeactivate interface):
import { CanDeactivate } from '@angular/router';
import { CanDeactivateComponent } from './app/can-deactivate';
export class ConfirmDeactivateGuard implements CanDeactivate<CanDeactivateComponent>
{
canDeactivate(target: CanDeactivateComponent)
{
if(target.hasChanges()){
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
Even though, this is a very trivial implementation, CanDeactivate uses a generic, so you need to specify what component type you want to deactivate.
In the Angular router of the component:
{
path: '',
component: SomeComponent,
canDeactivate: [ConfirmDeactivateGuard]
}
Last, like all other services on Angular, this guard needs to be registered accordingly:
@NgModule({
...
providers: [
...
ConfirmDeactivateGuard
]
})
export class AppModule {}
You can have multiple guards protecting a single route, which helps you implementing sophisticated use cases, where a chain of different checks is needed.
Upvotes: 11