4

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?

Hasan Raza
  • 55
  • 1
  • 3
  • 7
  • 1
    can you explain what exactly you are trying? seems like an XY scenario... – Suraj Rao Jan 30 '18 at 05:46
  • Can you specify any scenario – Shrey Kejriwal Jan 30 '18 at 05:47
  • `canDeactivate` router guard – Aravind Jan 30 '18 at 05:48
  • Does your application use Routing? I think it should. If it does, check https://angular.io/api/router/CanDeactivate this – Vinod Bhavnani Jan 30 '18 at 05:49
  • 1
    It is not very wise to do that bcz it helps in any memory leak issues. If you have anything created and it should not have to be on other routes which is a definite candidate to destroy it in `ngOnDestroy()` like some subscriptions. – Jai Jan 30 '18 at 05:55
  • Look into your [RouterReuseStrategy](https://angular.io/api/router/RouteReuseStrategy). It allows Angular to reuse Components that have been routed away from. – joshrathke Jan 30 '18 at 06:47
  • 1
    Check out this StackOverflow answer for a detailed code sample. https://stackoverflow.com/a/62409873/4109794 – Junaid Jun 16 '20 at 13:41

1 Answers1

11

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.

Marco Barbero
  • 1,460
  • 1
  • 12
  • 22