Conditional Guard with Angular

Nasreddine Skandrani
Front-End Tricks — TheBlog
1 min readMay 31, 2020

If you want to execute a guard depending on a condition, i will show you a simple way to do it.

You can find my online example here.

This solution is mostly needed when you use a guard provided by a library (internal or external to your company). The solution is to wrap the provided guard with another guard. Let say the guard is ExampleGuard and so your wrapper will be:

import { Injectable } from '@angular/core';import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';import { ExampleGuard } from './example.guard';@Injectable()
export class ConditionalGuard implements CanActivate {
constructor(private exampleGuard: ExampleGuard) {} canActivate(_route: ActivatedRouteSnapshot, _state:
RouterStateSnapshot): any {
//bypass guard here if (localStorage.getItem('bypassguard') === '1') {
return true;
}
// call your guard here
return this.exampleGuard.canActivate(_route, _state);
}}

Hope this helps!

Keep up with our content by following us @FrontEndTricks & don’t forget to give it some 👏👏👏.

~ Thank you ~

--

--