1

I'm trying to implement a global dirty checker in Angular. We have a solution that requires configuring each component, but I was hoping to generalize it more.

I wired up global code that would check each active component and then signal whether or not the user should be prompted. Or at least, I thought it was doing that. My initial plan was listing to router.events for NavigationEnd events and inspecting the current ActivatedRoute because it exposes a component property. However, that property is the type/class of the component and not the actual instance.

I have yet to find an API that exposes the current component instances. Does it exist or am I stuck?

UPDATE

The usecase I am struggling with is not route changes, but when the window closes. When window:beforeunload fires, I don't have any way to ask the component instances if they are dirty.

UPDATE 2 Created issue: https://github.com/angular/angular/issues/18634

pgreen2
  • 3,601
  • 3
  • 32
  • 59
  • Could you instead implement a generalized `canDeactivate` guard and assign that guard to each route? The canDeactivate *does* give you the instance of the component. – DeborahK Aug 09 '17 at 20:07
  • Yes, and I have that for route changes. Hopefully, `canDeactivateChild` will be implemented soon and will clean that up further. However, where I am currently struggling is when the user closes the window. I didn't clarify that in my question, but I will update that now. – pgreen2 Aug 09 '17 at 20:20
  • That may need to be a feature request because I don't think that there is anything to provide that for you at that point. You can post requests to: https://github.com/angular/angular/issues – DeborahK Aug 09 '17 at 20:27

1 Answers1

0

Warn user of unsaved changes before leaving page

https://medium.com/@amcdnl/angular-guards-more-than-security-c04be35adb00

GoNode5
  • 21
  • 1
  • 4
  • 1
    These are fine examples of how to solve the problem for a particular component. However, in our organization, I expect to have 100s if not 1000s of components and I would like to prevent everyone one of them requiring the same exact code each time. – pgreen2 Aug 11 '17 at 02:32