2

I am trying to find a way to alert user before exiting the screen. If they press "no" then it should not destroy. And if they press "ok" then carry on with destroy operations.

Does ngOnDestory has a event that happens before ngOnDestory? for example ngOnBeforeDestroying?

I am currently developing with Angular 4.

Aravind
  • 40,391
  • 16
  • 91
  • 110
User1911
  • 394
  • 1
  • 5
  • 22
  • Search for canDeactivate guard.It allows you to control the navigating away from a particular page.So suppose there is a page which allows user to fill up a form.So after filling half of the form the user tries to go to another page, than we can use this guard to confirm user if he really wants to navigate, because his form data will be lost on navigating. – pritesh Jun 18 '17 at 06:54

1 Answers1

3

yes, you should be using canDeactivate route guard.

Create a injectable service

@Injectable()
class CanDeactivateService implements CanDeactivate<TeamComponent> {


  canDeactivate(
    component: TeamComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return component.isDirty ;
 }
}

This can be used to determine if the page can be destroyed or not.

This should be configured in Routes as

RouterModule.forRoot([
      {
        path: '..', // path
        component: Comp, // name of the component
        canDeactivate: [CanDeactivateService]
      }
    ])
  ],

Read more here...

Angular's Official Demo

This can be achieved through dynamic component loading also. Follow steps here

Aravind
  • 40,391
  • 16
  • 91
  • 110
  • How can I achieve this if there are multiple components on the same route and I want to warn user before destroying each components i.e. route is not getting changed? – Ashwin Jun 20 '19 at 08:46
  • 3
    like @Ashwin said, i have tabs in a single page. Navigating through tabs the route does not change but the components get destroyed. How to alert the user and prevent this? – Andreas Hadjithoma Feb 26 '20 at 08:08