How to use Angular Guards

Recently I ran into a situation where a user would fill out a complex form and then accidentally click on another menu item within the web app. Doing so caused them to lose all the form data and was such a pain. I mean we could cache the form data but that adds another level of unnecessary complexity.

I started doing some research and came across Angular guards. These can really make your app robust and one can achieve some very complex behavior like authentication, role based security etc if done properly. But that’s another topic for discussion.

You can look at the stackblitz demo here.

I will explain the demo first. You have two links i.e. Link A and Link B. When you click on A it will show you a form. If you click on B without making any changes you will be taken to B. But if you make a change and then try switching to B it will display a message about unsaved changes. In a real world app you might want to display some sort of a pop up message asking for confirmation.

Now I will explain the code. We have a guard called Myguard that implements the CanDeactive interface. This only has one method:

interface CanDeactivate<T> { ... }

that you need to implement. One of the argument is your component that you can then use to handle deactivation logic. In our case we call a method into our component to check if the form is dirty or not. You also have to make sure to add the canDeactivate property on the target route. Like this:

const routes : Routes = [  

{    

path: 'link-a',

component: LinkAComponent,    

canDeactivate: [MyguardGuard]  

}, 

...]

If you look at the deactivate method inside the link A component it returns a promise that is then resolved by angular to do its magic. I am using Rxjs of operator to create an observable and then calling toPromise on it.

Here is the source code.

Leave a Reply

Your email address will not be published. Required fields are marked *