Thursday, December 28, 2017

How to set up a super simple "Are you sure you want to leave?" guard in an Angular 4 app!

The CanDeactivate stuff in bullet thirteen here proved hard for me to implement. I ended up going into the outermost module and adding something like this to the providers:

{
   provide: 'WhateverGuard',
   useValue: () => {
      return confirm('Are you sure you want to leave?');
   }
},

 
 

At the routing module, at an applicable route definition, we have an array of canDeactivate guards like so:

{
   path: 'whatever',
   canDeactivate: ['WhateverGuard'],
   component: WhateverComponent
},

 
 

Alright, the good news is that this works and that whenever you try to navigate away from whatever you are gonna be asked "Are you sure you want to leave?" but the bad news is that you will always be asked as much. What if I wanted to inject some conditionally logic and just return true if I don't want to torment the user with an unmerited question? I have not figured out what to do about that yet.

No comments:

Post a Comment